我一直在使用小部件工厂开发 jQuery 小部件。
一切都很好,只是我注意到,如果我在同一页面上的多个 DOM 元素上实例化小部件,则小部件内的任何对象都会在 DOM 元素之间共享,除了选项对象。
我认为所有对象和函数在小部件中都有自己的实例。我显然遗漏了一些东西,希望得到一些指导。
例如:
(function($) {
$.widget("a07.BearCal", {
options: { className : "test" },
_glbl: { something: "" },
_create: function() {
this._glbl.something = this.element.attr('class');
this.options.className = this.element.attr('class');
},
});
})(jQuery);
// Instantiate widget on .full
$('.full').BearCal();
//Should output full
console.log($('.full').data('BearCal')._glbl.something);
//Should output full
console.log($('.full').data('BearCal').options.className);
// Instantiate widget on .mini
$('.mini').BearCal();
//Should output mini
console.log($('.mini').data('BearCal')._glbl.something);
//Should output mini
console.log($('.mini').data('BearCal').options.className);
//Should output full but outputs mini
console.log($('.full').data('BearCal')._glbl.something);
//Should output full
console.log($('.full').data('BearCal').options.className);
此示例:http://jsfiddle.net/NrKVP/4/
提前致谢!
最佳答案
小部件的属性:
$.widget("a07.BearCal", {
// The stuff in here...
});
附加到您的小部件的原型(prototype)。小部件工厂了解 options
并知道它需要为每个小部件复制它们:您的 options
的行为符合您的预期,因为小部件工厂安排了此行为。小部件工厂对 _glbl
一无所知,因此它会留在原型(prototype)上,从而被小部件的所有实例共享。
如果您想要每个小部件的副本,您可以自己复制 _glbl
:
this._glbl = { something: this.element.attr('class') };
这将为每个小部件提供不同的 _glbl
对象。
演示:http://jsfiddle.net/ambiguous/UX5Zg/
如果您的_glbl
比较复杂,那么您可以使用$.extend
复制它并将某些内容
合并到:
this._glbl = $.extend(
{ },
this._glbl,
{ something: this.element.attr('class') }
);
如果您需要深层复制,您需要使用 true
作为 $.extend
的第一个参数。需要空对象 { }
,因为 $.extend
会将所有内容合并到其第一个对象参数中,并且您需要一个新副本。
关于javascript - jquery 小部件中的对象仅表现为一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12995039/