使jQuery样板支持链接
根据报告: 这个不支持链,看起来(原文如此)不像那么多人 使用插件链语法 如何才能改变它,使其符合要求?代码是:使jQuery样板支持链接,jquery,Jquery,根据报告: 这个不支持链,看起来(原文如此)不像那么多人 使用插件链语法 如何才能改变它,使其符合要求?代码是: /* * Project: * Description: * Author: * License: */ // the semi-colon before function invocation is a safety net against concatenated // scripts and/or other plugins which may not be
/*
* Project:
* Description:
* Author:
* License:
*/
// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
;(function ($, window, document, undefined) {
// undefined is used here as the undefined global variable in ECMAScript 3 is
// mutable (ie. it can be changed by someone else). undefined isn't really being
// passed in so we can ensure the value of it is truly undefined. In ES5, undefined
// can no longer be modified.
// window is passed through as local variable rather than global
// as this (slightly) quickens the resolution process and can be more efficiently
// minified (especially when both are regularly referenced in your plugin).
var // plugin name
pluginName = "pluginName",
// key using in $.data()
dataKey = "plugin_" + pluginName;
var privateMethod = function () {
// ...
};
var Plugin = function (element, options) {
this.element = element;
this.options = {
// default options
};
/*
* Initialization
*/
this.init(options);
};
Plugin.prototype = {
// initialize options
init: function (options) {
$.extend(this.options, options);
/*
* Update plugin for options
*/
},
publicMethod: function () {
// ...
}
};
/*
* Plugin wrapper, preventing against multiple instantiations and
* return plugin instance.
*/
$.fn[pluginName] = function (options) {
var plugin = this.data(dataKey);
// has plugin instantiated ?
if (plugin instanceof Plugin) {
// if have options arguments, call plugin.init() again
if (typeof options !== 'undefined') {
plugin.init(options);
}
} else {
plugin = new Plugin(this, options);
this.data(dataKey, plugin);
}
return plugin;
};
}(jQuery, window, document));
您目前不能做的是类似于
$('div').plugin().css('border','1px实心红色')代码>添加jQuery函数会破坏它。为什么一个插件不想支持链式链接?如何调整它以支持链式链接?不要在最后返回plugin
,只需返回this
您可能不想支持链接,因此可以返回插件的接口,例如
var coolPlugin = $('img').coolPlugin()
coolPlugin.play(500)
大多数插件使用的另一种选择是类似于coolPlugin('play',500)
谢谢,这很难看,但很有效。如果您返回this
而不是plugin
,您仍然可以使用数据属性进行过滤吗?例如,$(“.element”).defaultPluginName()$(“#element-1”).data('plugin_defaultPluginName').yourOtherFunction()代码>我喜欢这个关于样板的特性。