Created
September 13, 2012 21:20
-
-
Save avoinea/3717757 to your computer and use it in GitHub Desktop.
Solid and extensible jQuery plugins
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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