在现有插件中添加和覆盖功能

时间:2011-05-18 12:54:18

标签: javascript jquery

以下是我的插件:

(function($) {
    $.fn.myPlugin = function(options) {
        var opt = $.extend({}, $.fn.myPlugin.defaults, options);

        this.foo()
        {
            alert('test');
        }


    }
    $.fn.myPlugin.defaults = {
    };
});

现在我想扩展它而不触及原始插件,即我想要现有插件的全部功能+我想要的新功能。以下是我需要的新东西:

第一: 新插件“myPlugin2”的名称

第二: 应该在新插件中覆盖现有插件的“foo”功能:

function foo() {
    alert('test2');
}

第三: 我需要在我的新插件中添加一个方法,比如函数foo2(){}。

你能帮助我实现这个目标吗?

2 个答案:

答案 0 :(得分:2)

您需要在默认声明中定义默认名称和foo事件:

$.fn.myPlugin.defaults = {
  name: 'test',
  onFoo: function() {
           alert(this.name);
         },
  onFoo2: function() {
           // your default behaviour for foo2
         }
};

然后,当有人调用您的插件时,他们可以覆盖默认值,在这种情况下name

  $("#myControl").myPlugin({
    name: 'test2'
  });

请注意,它们不需要覆盖onFoo,因为它将显示带有test2的警报。无论如何,如果他们需要覆盖它来做一些不同的事情,那么他们应该:

  $("#myControl").myPlugin({
    name: 'test2',
    onFoo: function() {
             alert('onFoo overrired');
           },
    onFoo2: function() {
             alert('onFoo2 overrired');
           }
  });

在你的插件中,你调用foo方法为

(function($) {
    $.fn.myPlugin = function(options) {
        var opt = $.extend({}, $.fn.myPlugin.defaults, options);

        // if onFoo is defined then call it
        if (opt.onFoo) {
          opt.onFoo();
        }

        // if onFoo2 is defined then call it
        if (opt.onFoo2) {
          opt.onFoo2();
        }
    }

    $.fn.myPlugin.defaults = {
       name: 'test',
       onFoo: function() {
                alert(this.name);
              },
       onFoo2: function() {
                // your default behaviour for foo2
              }
    };
});

您应该将此技术用于要向插件用户公开的公共方法/属性。 我没有测试但应该工作

修改 您需要在调用之前检查事件是否已设置:

// if onFoo is defined (not null) then call it
if (opt.onFoo) {
  opt.onFoo();
}

您已经为onFoo和onFoo2设置了一个事件,但插件的用户可能会选择禁用它:

  $("#myControl").myPlugin({
    onFoo: null
  });

在这种情况下,虽然您已定义了onFoo事件,但插件的用户决定将其忽略,方法是将其设置为null。所以,即使你已经定义了一个事件,你也不会知道其他人会用它做什么,因此最好是安全起见并检查是否无效。

再一次,您需要小心向最终用户展示的内容,因为设置/取消设置事件不应该破坏插件的基本功能

答案 1 :(得分:0)

如果这是任何体面编码的插件,你就不应该改变它的方法。它应该做任何不应被称为内部函数的东西,即:

$.fn.oldPlugin = function() {

    var foo = function() {
       alert('old code');
    };
};

无法调用foo或覆盖它。

如果您不需要更改任何方法/功能,则可以使用$.extend($.fn.pluginName, {/*your methods/properties*/};

真正归结为:

  • 您希望扩展的插件是如何编码的
  • 如果您想覆盖或只是扩展其功能