Skip to content

Instantly share code, notes, and snippets.

@avoinea
Created September 13, 2012 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save avoinea/3717757 to your computer and use it in GitHub Desktop.
Save avoinea/3717757 to your computer and use it in GitHub Desktop.
Solid and extensible jQuery plugins
// Top namespace
if( !window.Alien ){
var Alien = {"version": "1.0"};
}
// Constructor
Alien.Ship = function(context, options){
var self = this;
self.context = context;
self.settings = {
width: 800,
height: 600
};
if(options){
jQuery.extend(self.settings, options);
}
self.initialize();
};
// Prototype
Alien.Ship.prototype = {
initialize: function(){
var self = this;
// Bind some events
self.context.bind('width-changed', function(evt, data){
self.handle_width(data);
});
self.context.bind('height-changed', function(evt, data){
self.handle_height(data);
});
// Do some initialization
self.context.css('background-color', 'gray');
},
handle_width: function(data){
var self = this;
self.settings.width = data.width;
},
handle_height: function(data){
var self = this;
self.settings.height = data.height;
}
};
// jQuery plugin
jQuery.fn.AlienShip = function(options){
return this.each(function(){
var context = jQuery(this);
var ship = new Alien.Ship(context, options);
context.data('AlienShip', ship);
});
};
// Call it
jQuery('.car').AlienShip({width: 1024, height: 800});
// Access it
jQuery('.car').data('AlienShip');
// Extend it
Alien.Ship.prototype.handle_width = function(data){
var self = this;
self.settings.width = data.width / 2;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment