2012-12-28 34 views
0

我有一个简单的插件,它有init,close和open函数。我有一个调用这个插件的html模板数组。只是对于某个模板,我想对这个插件做一些稍微不同的行为,比如说可以在open函数中添加一个不同的类,并在关闭时删除相同的类。什么是做这件事的优雅方式?我应该找到html的id并在同一个插件的open和close函数中做一个if else,或者有更好的方法吗?如何调用具有稍微不同行为的插件?

;(function ($, window, document, undefined) { 

    function Plugin(element, options) { 
      Window = this; 
      this.element = element; 
      this._name = pluginName; 
      this.init(element); 
     } 

    Plugin.prototype = { 
      init: function(element) { 
    }, 
    close:function(e){ 
    //removes a class and hides the element 
    }, 
    open:function(element){ 
    //adds a class and shows the element 
    } 

    } 
//Extend Global jQuery (where we actually add the plugin!) 
    $.fn[pluginName] = function (options) { 
     plugin = $.data(window, 'plugin_' + pluginName); 
     if (!(plugin instanceof Plugin)) { 
      $.data(window, 'plugin_' + pluginName, 
      plugin = new Plugin(this, options)); 
     } 
     return $Extend(this).each(function() { 
      $.data(this, 'plugin_' + pluginName, plugin); 
     }); 
    }; 

}(jQuery, window, document)); 

回答

0

我会通过添加一个可选的对象句柄初始化设置您传递到插件您options PARAM。

从本质上讲,只需确保options参数是所有相关的初始化方法访问,然后执行类似如下:

open: function(element){ 
var initClass = options.initClass || "DEFAULTVALUE"; 
//adds "initClass" as a class and show the element 
} 

的||是一个速记技巧,说如果“options.initClass”不存在,则默认下一个值。您可以了解有关||的更多信息here

+0

或者使用大多数jQuery插件中使用的'extend()'成语将用户的选项合并到默认选项对象中。 – Barmar

+0

您必须做的另一件事是记住每个元素使用的选项。这可以使用'data()'完成。 – Barmar

+0

@Barmar两个好的指针。 – adamb

0

如果你有一组选项:当你创建你的插件,你可以在一个实例,然后

function MyPlugin(options){ 
    options = $.extend({}, MyPlugin.options, options); 

    options.add(); 
} 

MyPlugin.options = { 
    width: 200, 
    height: 500, 
    add: function() { 
     alert("add was called"); 
    }, 
    delete: function() { 
     alert("delete was called"); 
    } 
}; 

当你通过选项加入到你的插件,你可以覆盖默认值通过设置其选项覆盖一个或多个属性:

var plugin = new MyPlugin({ 
    width: 100, 
    add: function() { 
     alert("My add was called!"); 
    } 
}); 

在前面的cod e,一个警报将显示“我的添加被称为!”。

相关问题