public
Last active — forked from ibolmo/Class.Mutators.jQuery.js

  • Download Gist
Class.Mutators.jQuery.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Class.Mutators.jQuery = function(name){
var self = this;
jQuery.fn[name] = function(arg){
if ($type(arg) == 'string'){
var instance = this.data(name);
if($type(instance[arg]) == 'function'){
var returns = instance[arg].apply(instance, Array.slice(arguments, 1));
return (returns == instance) ? this : returns;
}
if(arguments[1] != null){
instance[arg] = arguments[1];
return this;
}
return instance[arg];
} else {
if(this.data(name)) return this.data(name);
this.data(name, new self(this.selector, arg));
return this;
}
};
};
Person.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
var Person = new Class({
 
Implements: Options,
 
options: {
height: 'tall',
weight: 'fat'
},
 
jQuery: 'person', // must be after options definition
 
awesome: true,
 
initialize: function(selector, options){
this.setOptions(options);
this.jqueryObject = jQuery(selector);
},
 
dance: function(whichDance){
alert(whichDance);
return this;
 
}
 
});
usage.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// regular javascript api
var bob = new Person('#dude',{ height: 'short' });
bob.dance('salsa'); // dances the salsa and returns bob
bob.awesome; // returns true
bob.awesome = false; // set the property to something else
 
// jQuery api
$('#bob').person({ height: 'short' }); // instantiate with options
$('#bob').person(); // returns the class instance since it's already been instantiated
// or in other words, returns and object like `bob` from above
$('#bob').person('dance', 'salsa'); // dance the salsa and returns the jQuery object
// because the class returns `this`, (magic from the mutator)
$('#dude').person('awesome'); // returns true, not the jQuery object because the
// method doesn't return the instance, it returns a value
$('#dude').person('awesome', false); // reassign the property

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.