覆盖jQuery函数-最佳实践 [英] Overriding jQuery functions - best practice

查看:85
本文介绍了覆盖jQuery函数-最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Web应用程序正在使用许多JQuery插件,例如Datatables,以及相应的Row Reordering and Sorting插件.

My web application is using a number of JQuery plugins such as the Datatables, and it's corresponding Row Reordering and Sorting plugins.

问题是我们需要添加一些修复程序来解决令人讨厌的IE8不一致问题.

The problem is that we need to add some fixes to account for annoying IE8 inconsistencies.

例如,在一个插件_mouseDrag()方法中,我们需要在开始时添加一些额外的逻辑.有没有一种方法可以在不修改插件源代码的情况下覆盖此功能?

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?

在OO语言中,您通常会覆盖类方法,添加一些逻辑,然后调用super()方法以避免修改API的源代码.

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.

因此,我想知道如何在不修改库本身的情况下最好地支持JavaScript.

Therefore, I am wondering how we can best support this in JavaScript without modifying the library itself.

谢谢

更新的问题

根据以下示例,如何覆盖我的_mouseDrag函数,该函数在以下第三方库中的存在如下:

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){

...

}

我该如何精确覆盖呢?

推荐答案

尝试一下(请参阅演示: http://jsfiddle.net/2rZN7/):

Try this (see Demo: http://jsfiddle.net/2rZN7/):

(function ($) {
  var oldPluginFunction =  $.fn.pluginFunction;

  $.fn.pluginFunction = function () {
    // your code
    return oldPluginFunction.call(this);
  };
})(jQuery);

来自演示:

HTML:

<span id="text1">text1</span>
<span id="text2">text2</span>

JavaScript:

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

这篇关于覆盖jQuery函数-最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆