I\'m trying to create a plugin with ability to update options after initialization. I\'ve started with simple plugin, which will help me to understand plugin\'s logic. So he
It is a question of scope, you need to change the scope of the options - normally you would not but in this case you do, so you change to modify the original options in the $.extend(
, and give it a reference thus:
;(function ($) {
var self = this;
self.defaults = {
message: 'This is default message'
};
self.options = {};
var methods = {
init: function (options) {
options = $.extend(self.options, self.defaults, options);
return this.each(function () {
$(this).click(function () {
alert(options.message);
});
});
},
option: function (key, myvalue) {
if (myvalue) {
self.options[key] = myvalue;
} else {
return self.options[key];
}
}
};
$.fn.clickAlert = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
//some error that method doesnt exist
}
};
})(jQuery);
jQuery(document).ready(function ($) {
$('.show').clickAlert();
$('.change').click(function () {
$('.show').clickAlert('option', 'message', 'Updated message');
});
});