Skip to content

Instantly share code, notes, and snippets.

@bencooling
Last active August 29, 2015 14:01
Show Gist options
  • Save bencooling/c145aa282bb34c004e82 to your computer and use it in GitHub Desktop.
Save bencooling/c145aa282bb34c004e82 to your computer and use it in GitHub Desktop.
jQuery plugin with public api, pub sub dependency for plugin events
/*
|--------------------------------------------------------------------------
| jQuery plugin
|--------------------------------------------------------------------------
| By Ben Cooling (https://github.com/bencooling, http://bcooling.com.au)
|
| Plugin with:
| - Public api for programitically calling plugin methods
| - Options for overiding default configuration values
| - AMD compatability
| - jquery pubsub dependency for subscribing to plugin events
|
*/
define(['jquery'], ['jquery.pubsub'], function($){
$.fn.clicky = function(options){
// default values
var o = {
clicked : 'closed',
open : function(){
$.Topic('clicky.open').publish();
this.clicked = 'open';
},
close : function(){
$.Topic('clicky.closed').publish();
this.clicked = 'closed';
},
create : function(){
$(this.el).on('click', function(){
var api = $(this).data('api'); //jquery hijacks this with DOM element within event handler
if (api.clicked==='open')
api.close();
else
api.open();
});
},
destroy : function(){
$(this.el).off('click').removeData('api');
}
};
$(this).each(function(i, el){
var $el = $(el),
api = $.extend(options, o);
api = $.extend({el:el}, api);
$el.data('api', api);
$el.data('api').create();
});
return this;
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment