Skip to content

Instantly share code, notes, and snippets.

@mgvez
Created November 30, 2012 21:02
Show Gist options
  • Save mgvez/4178579 to your computer and use it in GitHub Desktop.
Save mgvez/4178579 to your computer and use it in GitHub Desktop.
First version of a demonstration on how to create an abstract jQuery plugin. But we're not finished yet...
;(function ( $, window, document, undefined ) {
var pluginName = 'abstractButton';
var defaults = {
autoActivate : true
};
var out = function(){
$(this).data('tl').reverse();
};
var hover = function(){
$(this).data('tl').play();
};
var PluginPrototype = {
init : function(name, el, options) {
this.name = name;
this.el = el;
this.$el = $(el);
this.options = $.extend({}, defaults, options);
this.activate();
this.setAnimation = options.setAnimation;
if(this.options.autoActivate === false) {
this.deactivate();
}
},
setTimeline : function() {
var element = this.$el;
if(element.data('tl')) return;
var tl = new TimelineLite({onComplete: function(){
element.data('tl').stop();
}});
tl.stop();
element.data('tl', tl);
this.setAnimation(element, tl);
},
getTimeline : function(element) {
return element.data('tl');
},
activate : function(context) {
this.setTimeline();
this.$el.on('mouseenter.buttonGrange', hover).on('mouseleave.buttonGrange, click.buttonGrange', out);
},
deactivate : function(context){
this.$el.off('.buttonGrange');
}
};
$.fn[pluginName] = function(options) {
var input = arguments;
if ( this.length ) {
return this.each(function () {
//plugin is not instanciated. Create it (requires an object or null as arguments)
if (!$.data(this, pluginName)) {
if(typeof options === 'object' || !options){
//create an instance of our concrete plugin
var instance = Object.create(PluginPrototype);
instance.init(pluginName, this, options);
$.data(this, pluginName, instance);
} else {
$.error( 'Plugin jQuery.' + pluginName + " has not yet been instanciated." );
}
} else if(typeof options === 'string') {
//methods that begin with _ are private
if(options[0]==='_') {
$.error( 'Plugin jQuery.' + pluginName + ' : method ' + options + ' is private');
return;
}
//plugin is instanciated, get it
var controller = $.data(this, pluginName);
if(controller[options]) {
controller[options](Array.prototype.slice.call(input, 1));
} else {
$.error( 'Plugin jQuery.' + pluginName + " has no method " + options);
}
} else {
$.error( 'Plugin jQuery.' + pluginName + " has already been instanciated.");
}
});
}
};
})( jQuery, window, document );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment