Reputation: 19854
My web application is using a number of JQuery plugins such as the Datatables, and it's corresponding Row Reordering and Sorting plugins.
The problem is that we need to add some fixes to account for annoying IE8 inconsistencies.
So, for example, in one of the plugins _mouseDrag() method we need to add some extra logic at the start. Is there a way to override this function without modifying the plugin's source code?
In an OO language you would typically override a class method, add some logic and then call the super() method to avoid modifying an API's source code.
Therefore, I am wondering how we can best support this in JavaScript without modifying the library itself.
Thanks
Updated Question
Based on the example below, how do I override my _mouseDrag function which exists as the following in the 3rd party library:
(function( $, undefined ) {
$.widget("ui.sortable", $.ui.mouse, {
_mouseDrag: function (event){
...
}
How do I override this exactly?
Upvotes: 4
Views: 14525
Reputation: 121
You can override plugins method by prototype it in a separate file without modifying original source file as below::
(function ($) {
$.ui.draggable.prototype._mouseDrag = function(event, noPropagation) {
// Your Code
},
$.ui.resizable.prototype._mouseDrag = function(event) {
// Your code
}
}(jQuery));
Now put your logic here or original code with your new idea that is needed in your project.
Upvotes: 1
Reputation: 30453
Try this (see Demo: http://jsfiddle.net/2rZN7/):
(function ($) {
var oldPluginFunction = $.fn.pluginFunction;
$.fn.pluginFunction = function () {
// your code
return oldPluginFunction.call(this);
};
})(jQuery);
From Demo:
HTML:
<span id="text1">text1</span>
<span id="text2">text2</span>
JavaScript:
// define and use plugin
$.fn.pluginFunction = function (color) {
return this.each(function () {
$(this).css('color', color);
});
};
$('#text1').pluginFunction('red');
// redefine and use plugin
(function ($) {
var oldPluginFunction = $.fn.pluginFunction;
$.fn.pluginFunction = function () {
$(this).css('font-size', 24)
return oldPluginFunction.apply(this, arguments);
};
})(jQuery);
$('#text2').pluginFunction('red');
Upvotes: 9