【发布时间】:2019-05-13 19:23:59
【问题描述】:
我正在开发一个 jQuery 插件,但我遇到了变量“范围”的问题。每个插件都需要跟踪一个相当大的多维数组,以及 jQuery 插件附加到的根元素。
如下图,我在插件代码的顶部定义了var $rootEl = null;和var multidArray = null;;但是,当我在多个元素上运行 $(anySelector).pluginName("value"); 时(或者当我使用不同的选择器调用 .pluginName() 两次时),这些变量似乎没有被沙盒化/作用于插件实例,因此第二个实例会覆盖这两个值并且第一个实例在 DOM 中看起来是空白的(因为所有 jQuery 操作都应用于 $rootEl,而原始值在第二个 jQuery 插件调用时被覆盖)。
(function ($) {
var $rootEl = null;
var multidArray = null;
directChildren = function(uuid) {
return $rootEl.children("[data-uuid=" + uuid + "]");
},
incrementCounter = function() {
this.counter++;
},
resetGenIteration = function() {
this.counter = 0;
},
process = function(item) { // Will be called from a callback(val) in another
// javascript file but still needs to have access to the local variables
// of the current jQuery plugin
incrementCounter();
...
},
...
$.fn.pluginName = function(rootvar) {
this.each(function() {
$rootEl = $(this);
resetGenIteration();
populate(rootvar);
$rootEl.addClass("pluginName").delegate("div", "click", divClick);
});
}
}(jQuery));
昨天我试图将插件转换为使用 init 和 this.varname 来存储值,它似乎为插件的每个实例正确地保留了 this.$rootEl 属性,但我不得不将我的所有函数移到里面的var PluginName = { ... } 并将它们从funcName = function() 切换到funcName: function() 以便能够看到插件实例的“本地”变量。然后我遇到了许多未定义函数的错误,因此我尝试在所有函数调用前加上this. 和PluginName.,分别读取为this.functionName() 或PluginName.functionName(),这对某些函数有效,但不是全部。我的一些函数是从另一个运行回调函数并将数据传递给它的 jQuery 插件调用的,在这些情况下,this.$rootEl 变为 undefined。
(function ($){
var PluginName = {
init: function(options, rootEl) {
this.options = $.extend({}, this.options, options);
this.rootEl = rootEl;
this.$rootEl = $(rootEl);
this.setListeners();
return this;
},
options: {
rootvar: "test"
},
...
setListeners:function (){
var self = this;
this.$rootEl.on("div", "click", function () {
$.proxy(self.divClick, self);
});
}
};
...
$.fn.pluginName = function(options) {
this.init = function(options, rootEl) {
this.options = $.extend({}, this.options, options);
this.rootEl = rootEl;
this.$rootEl = $(rootEl);
this.multidArray = null;
return this;
};
this.each(function() {
var plugInstance = Object.create(PluginName);
plugInstance.init(options, this);
$.data(this, 'pluginName', plugInstance);
});
}
}(jQuery));
如何重构我的代码以存储多维数组和根元素,以使只有给定插件才能在内部检索和修改?我肯定不应该将.data() 用于大型数组吗?
谢谢!
【问题讨论】:
标签: javascript jquery scope jquery-plugins