I have simplified the code below to outline the issue. When I invoke plugin's method like this $('#element').plugin('hide');
it works, but when I call it from the inner show()
method, like this.hide()
it doesn't work or it calls the jQuery hide()
method.
I tried var self = this
, $.proxy()
, apply()
, call()
but without success. Here is the jsBin
;(function ($, window, document, undefined) {
var defaults = {
type: 'standard',
};
var methods = {
init: function(options){
console.log('IN - INIT()');
if(options){
$.extend(defaults, options);
}
},
show: function(arg){
console.log('IN - SHOW()');
var $this = this; // Here might be the problem
this.addClass(arg.type);
this.find('.close-button').on('click', function(){
$this.hide(); // Here might be the problem
});
},
hide: function(){
console.log('IN - HIDE()');
}
};
$.fn.plugin = function(method){
var args = arguments;
var $this = this;
return this.each(function(){
if(methods[method]){
return methods[method].apply($this, Array.prototype.slice.call(args, 1));
}else if (typeof method === 'object' || ! method){
return methods.init.apply($this, Array.prototype.slice.call(args, 0));
}else{
$.error('Method ' + method + ' does not exist on jQuery.plugin');
}
});
};
}(jQuery, window, document));