This method allows you to add a JavaScript constructor to the jQuery, and then manage the state of an instance with the jQuery API. For example:
var MyObject = function(selector, options){
this.jQuery = $(selector);
this.options = $.extend(this.defaults, options);
}; MyObject.prototype = {
defaults: {
one: 1,
two: 2
},
foo: 'bar',
addArgs: function(arg, arg2, arg3){
return arg + arg2 + arg3;
},
returnThis: function(){
return this;
}
};
jQuery.addObject('myNameSpace', MyObject);
Now you can use your object like this:
// Create an instance stored on #element
$('#element').myNameSpace({
one: 'one',
two: 'two'
});
$('#element').myNameSpace('foo'); // => 'bar'
$('#element').myNameSpace('foo', 'baz');
$('#element').myNameSpace('foo'); // => 'baz'
$('#element').addArgs(1,2,3); // => 6
If the method returns this
, then through the jQuery API it will return the jQuery.
$('#element').myNameSpace('returnThis').css().myNameSpace('foo', 'bar').fadeOut();
var instance = $('#element').myNameSpace(); // called with no args, after already instantiated, returns the instance
// or just get it from the data
var instance = $('#element').data('myNameSpace');
instance.addArgs(1,1,1); // => 3
instance.returnThis().foo; // => 'baz'
QUnit is a submodule of this repo. Run it as follows:
git submodule init
git submodule update
Then pop open Test/index.html
This chunk of code is moo4q's twin sister. They both do the same thing, interact with JavaScript objects through jQuery's simple API; moo4q just gets 14k of the rockin' MooTools inheritance API and language extensions as well.