如何在jQuery UI小部件工厂小部件中声明静态/类变量 [英] how to declare a static/class variable in a jquery ui widget factory widget
问题描述
关于jQuery ui小部件工厂...
Regarding the jquery ui widget factory...
拥有在所有实例之间共享的静态变量/类级别变量的最佳方法是什么?
What is the best way to have a static variable/class level variable that is shared amongst all instances?
例如
$.widget("ui.staticTest", {
staticVar:'unchanged',
test: function(a){
if(a){
this.staticVar= a;
}
alert(JSON.stringify(this.staticVar));
}
});
$('#test').staticTest();
$('#parent').staticTest();
$('#test').staticTest('test','changed');
$('#parent').staticTest('test');
在上面的
中,如果staticVar是静态的,则$('#parent').staticTest('test');会提醒已更改",但会提醒未更改".
in the above, if staticVar were static, $('#parent').staticTest('test'); would alert 'changed' but instead it alerts 'unchanged'.
(如果您想玩的话,此代码位于jsfiddle上: http://jsfiddle.net/alzclarke/Sx8pJ/)
(this code is on jsfiddle if you wanna have a play: http://jsfiddle.net/alzclarke/Sx8pJ/)
我能想到的解决方案很丑:
The solutions i can think of myself are ugly:
1)$('body').data('sharedVariable',myData)-这似乎不是一个好习惯,如果有人或某物清除了数据主体该怎么办 2)将其存储在原型名称空间中= $ .ui.staticTest.prototype.staticVar = myData; 这也会敲响警钟
1) $('body').data('sharedVariable', myData) - this doesn't seem like good practice, what if someone or something clears the body of data 2) store it in the prototype namespace e.g. = $.ui.staticTest.prototype.staticVar = myData; this also rings alarm bells
推荐答案
关闭是您的答案
(function($) {
var staticVariable = '';
$.widget('ui.newWidget', {
options: {
},
_init: function() {
}
});
})(jQuery);
staticVariable仅在您定义的窗口小部件的范围内可用,因为它包装在立即调用的匿名函数中(就像您应该已经为jquery/jquery ui插件所做的那样.
staticVariable will only be available in the scope of the widget you just defined since it's wrapped up in a anonymous function that's called immediately (like you should already be doing for your jquery/jquery ui plugins.
这篇关于如何在jQuery UI小部件工厂小部件中声明静态/类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!