Overriding jQuery functions - best practice

13,884

Solution 1

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');

Solution 2

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.

Share:
13,884
DJ180
Author by

DJ180

Updated on June 04, 2022

Comments

  • DJ180
    DJ180 about 2 years

    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?

  • DJ180
    DJ180 almost 12 years
    Would you mind explaining the function ($) part and the (jquery) at the end? Thanks!
  • Admin
    Admin almost 12 years
    @DJ180 Look up "IIFE" (Immediately-Invoked Function Expression)
  • DJ180
    DJ180 almost 12 years
    I see. This sounds exactly what I'm looking for. Will try it out first. Thanks
  • Matt
    Matt almost 12 years
    @DJ180 (& cc Speransky): You might want to pass any arguments the function receives to the old function, by changing .call(this) to .apply(this, arguments).