JQuery Method For Plugin
Shows how to add a method function to a jquery plugin
by Alvin Olavarrieta
HTML
<div style="display:none;" id="test">Yo</div>
JavaScript
var t = $('#test');
t.on('show', function () {
console.log('show');
});
t.on('hide', function () {
console.log('hide');
});
t.on('update', function () {
console.log('update');
});
var methods = {
init: function (options) {
var self = this;
settings = $.extend({},$.fn.plugin2.defaults, typeof options == 'object' && options);
if (typeof option == 'string') {
eval(option)();
} else {
self.show();
self.trigger('show');
}
self.html('<b>' + settings.test + '</b>');
},
show: function () {
this.show();
this.trigger('show');
},
hide: function () {
this.hide();
this.trigger('hide');
},
update: function (content) {
this.html(content);
this.trigger('update');
}
};
$.fn.plugin2 = function (methodOrOptions) {
if (methods[methodOrOptions]) {
return methods[methodOrOptions].apply($(this), Array.prototype.slice.call(arguments, 1));
} else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
// Default to "init"
return methods.init.apply($(this), arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.plugin');
}
};
$.fn.plugin = function (option) {
var self = $(this);
options = $.extend({
test: 'Test'
}, typeof option == 'object' && option);
if (typeof option == 'string') {
eval(option)();
} else show();
$.fn.plugin.method = function (text) {
self.html('<strong>' + text + '</strong>');
};
$.fn.plugin.toggle = function () {
self.fadeToggle();
};
self.html('<strong>' + options.test + '</strong>');
function show() {
self.show();
self.trigger('show');
}
function hide() {
self.hide();
self.trigger('hide');
}
};
$.fn.plugin2.defaults = {
test: 'Test'
}
t.plugin2();
t.plugin2('update', 'Rickey');