2013-08-07 84 views
0

我讀了很多關於它的內容,但是我所做的並沒有工作。我使用jquery plugin boilerplate如何從外部調用公共方法jquery插件?

我有一個叫做「defaultPluginName」插件和我有內部插件的公共方法:

sayHey: function(){ 
    alert('Hey!'); 
} 

我想調用這個方法outsise,這樣的事情:

$('#test').defaultPluginName('sayHey'); 

,但不工作,按照這裏一個小漁鏈接給你一個更好的看法我的問題: http://jsfiddle.net/TCxWj/

回答

2

你試圖調用的方法不公開所以你需要改變你的插件才能從插件外部觸發它。

在這裏看到你如何做到這一點:https://github.com/jquery-boilerplate/jquery-boilerplate/wiki/Another-extending-jQuery-boilerplate

基本上你需要改變

$.fn[ pluginName ] = function (options) { 
    return this.each(function() { 
     if (!$.data(this, "plugin_" + pluginName)) { 
       $.data(this, "plugin_" + pluginName, new Plugin(this, options)); 
     } 
    }); 
}; 

$.fn[pluginName] = function (arg) { 
    var args, instance; 

    // only allow the plugin to be instantiated once 
    if (!(this.data('plugin_' + pluginName) instanceof Plugin)) { 

     // if no instance, create one 
     this.data('plugin_' + pluginName, new Plugin(this)); 
    } 

    instance = this.data('plugin_' + pluginName); 

    /* 
    * because this boilerplate support multiple elements 
    * using same Plugin instance, so element should set here 
    */ 
    instance.element = this; 

    // Is the first parameter an object (arg), or was omitted, 
    // call Plugin.init(arg) 
    if (typeof arg === 'undefined' || typeof arg === 'object') { 

     if (typeof instance['init'] === 'function') { 
      instance.init(arg); 
     } 

    // checks that the requested public method exists 
    } else if (typeof arg === 'string' && typeof instance[arg] === 'function') { 

     // copy arguments & remove function name 
     args = Array.prototype.slice.call(arguments, 1); 

     // call the method 
     return instance[arg].apply(instance, args); 

    } else { 

     $.error('Method ' + arg + ' does not exist on jQuery.' + pluginName); 

    } 

}; 

然後,它會拿起你的方法。

希望它有幫助。