2011-05-18 47 views
1

下面是我的我的插件:在现有的插件添加和压倒一切的功能

(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的(){}。

你能帮我实现吗?

+1

该代码在语法上不合法的基本功能。 – Pointy 2011-05-18 13:08:32

+0

你看过http://docs.jquery.com/Plugins/Authoring吗?它可能有帮助... – 2011-05-18 13:21:37

回答

2

您需要在您的默认值来定义你的默认名称和Foo事件DECL aration:

$.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事件,你的插件的用户决定ignor通过将其设置为null。所以,即使你已经定义了一个事件,你永远不知道别人会用它来做什么,因此最好保持安全并检查是否为空。

再次,你需要小心你暴露给最终用户的东西,因为设置/取消设置的事件不应该打破你的插件

+0

这对我来说很好 – 2011-05-18 15:15:50

+0

有一个问题,如果(opt.onFoo){opt.onFoo(); }因为我已经在做$ .extend({},$ .fn.myPlugin.defaults,options); – 2011-05-18 15:44:48

+0

@Rocky Singh请参阅我在答案中添加的说明 – 2011-05-18 17:37:09

0

如果这是任何体面编码的插件,你不应该能够改变它的方法。它应该作出任何这并不意味着要调用一个内部函数,即:

$.fn.oldPlugin = function() { 

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

有没有办法来调用foo或覆盖它。

如果您不需要更改任何的方法/函数,那么你可以使用$.extend($.fn.pluginName, {/*your methods/properties*/};

什么这一切真的可以归结为是:

  • 如何你想扩展插件编码
  • 如果你想覆盖或只延长它的功能