In the following code i tried to extend my test plugin. I want to add a new method definition to existing plugin.
(function($) {
var settings = {
bg: 'white'
};
var methods = {
init: function(options) {
options = $.extend({}, options, settings);
return this.each(function () {
$(this).data("test", options);
});
},
whiten: function() {
var options = this.data("test");
this.css('background-color', options.bg);
}
};
$.fn.test = 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 {
$.error('Method ' + method + ' does not exist');
}
}
})(jQuery);
// New Method Definition
var methods = {
newMethod: function(){
alert('umut');
}
};
// Extending test plugin with newMethod
$.fn.extend(true,$.fn.test, methods );
$(document).ready(function() {
$('ul').test().css('background-color', 'wheat');
$('#go').click(function() {
$('ul').test("whiten");
// Calling newMethod
$('ul').test("newMethod");
});
});
But i got following error at firebug console:
uncaught exception: Method newMethod does not exist
How can i extend
var methods = {
}
block inside my test plugin?
Here is the jsfiddle link.
Edit: I’m changing my answer. This may be the simpler solution, since it requires less code change. Add
methodsas a property of your plugin. Add this line after you define your plugin function:This needs to be inside your closure that defines the plugin. The rest of your code should just work, extending
testvia$.extend()as you are already doing.Here’s my original answer:
If you want to be able to extend your plugin in this way, your plugin must expose a way to do so. You could add
methodsas a property insettingsand then deeply extendsettings.methodswithoptions.methodsin yourinitmethod.If you intend for
settingsto be the defaults, andoptionsto override settings, you’ve got your arguments reversed in your call to.extend(). Reverse your arguments, then addtrueas the first parameter to make it a deep extend:Then put your methods in
settings:Then, instead of extending your plugin’s methods via
$.extend(), do it in yourinitcall: