我有一个简单的插件,其中包含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));I have a simple plugin which has init, close and open functions in it. I have an array of html templates which invoke this plugin. Only for certain template, I want to do slightly different behavior to this plugin, lets say add a different class in the open function and remove the same class when closed. What is an elegant way of doing it? Should I find the id of the html and do an if else within the open and close functions within the same plugin or is there a better way to do it?
;(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));最满意答案
我会通过在您传递给插件的options参数中添加一个可选对象来处理初始化设置。
基本上,只需确保所有相关初始化方法都可以访问options参数,然后执行以下操作:
open: function(element){ var initClass = options.initClass || "DEFAULTVALUE"; //adds "initClass" as a class and show the element }|| 是一个速记技巧,表示如果“options.initClass”不存在,则默认为下一个值。 您可以了解有关||的更多信息 在这里 。
I would handle initialization settings by added an optional object to your options param that you pass into the plugin.
Essentially, just make sure the options param is accessible to all relevant initialization methods, then do something like the followings:
open: function(element){ var initClass = options.initClass || "DEFAULTVALUE"; //adds "initClass" as a class and show the element }The || is a shorthand trick that says if "options.initClass" doesn't exist, default the next value. You can learn more about || here.
更多推荐
发布评论