Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ryanflorence/320369 to your computer and use it in GitHub Desktop.
Save ryanflorence/320369 to your computer and use it in GitHub Desktop.
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;
}
};
};
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;
}
});
// 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment