Reputation: 470
I was trying to override a method in this jQuery plugin which follows a "jQuery lightweight plugin boilerplate" pattern referenced in this Smashing Magazine article, however I seem to be missing something. [Edit: turns out the pattern intentionally makes the method private.]
$.fn.mbp
exists when I test for it. But when I use the following syntax to override one of its method, there is no error, and the plugin method is not overridden.
$.fn.mbp.loadFiles = function() {
alert('test')
};
Upvotes: 0
Views: 612
Reputation: 38150
As Tomalak said they the function is protected however it isn't out of reach.
As it stores an instance of the mbp object in the jquery data storage we can grab the constructor of this object and overwrite the function.
From your code line 360:
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new MBP( this, options ));
}
else {
if (options == 'options') {
return $.data(this, 'plugin_' + pluginName).options;
}
}
});
}
Overwrite it:
$.data( $('<div/>').mbp()[0], 'plugin_mbp').constructor.prototype.loadFiles = function() {
// ...
}
However this is not really a very clean solution so you might think of another approach ;)
Upvotes: 3
Reputation: 338228
The plugin uses this appoach:
(function ($) {
function MBP() {
// ...
}
MBP.prototype.loadFiles = function () {
// ...
};
$.fn.mbp = function () {
return this.each(function () {
var mbp = new MBP();
// ...
});
};
})(jQuery)
Bottom line: Due to the enclosing function, the MBP constructor is private. You cannot modify it (at least not without modifying the source code of the plugin).
Upvotes: 1
Reputation: 1376
You have to make sure that your code runs after the plugins code thus making sure it is overridden. One way of doing this is logging in your console another one is by using a break point and the testing if your code is hit before or after.Moreover I noticed that you are calling mbp
while the function mentioned in your link is MBP
.Notice the case difference.Hope it helps
Upvotes: 0