如何在 jquery ui 小部件工厂小部件中声明静态/类变量 [英] how to declare a static/class variable in a jquery ui widget factory widget
问题描述
关于 jquery ui 小部件工厂...
在所有实例之间共享静态变量/类级别变量的最佳方式是什么?
例如
<上一页>$.widget("ui.staticTest", {staticVar:'不变',测试:函数(a){如果一个){this.staticVar=一个;}警报(JSON.stringify(this.staticVar));}});$('#test').staticTest();$('#parent').staticTest();$('#test').staticTest('test','changed');$('#parent').staticTest('test');在上面,如果 staticVar 是静态的,$('#parent').staticTest('test');会提示已更改",但会提示未更改".
(如果你想玩的话,这段代码在 jsfiddle 上:http://jsfiddle.net/alzclarke/Sx8pJ/)
我能想到的解决方案很丑:
1) $('body').data('sharedVariable', myData) - 这似乎不是一个好习惯,如果有人或某事清除了数据主体怎么办2)将其存储在原型命名空间中,例如= $.ui.staticTest.prototype.staticVar = myData;这也敲响了警钟
闭包就是你的答案
(函数($){var 静态变量 = '';$.widget('ui.newWidget', {选项: {},_init:函数(){}});})(jQuery);
staticVariable 仅在您刚刚定义的小部件的范围内可用,因为它包含在一个立即调用的匿名函数中(就像您应该已经为您的 jquery/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?
e.g.
$.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');
in the above, if staticVar were static, $('#parent').staticTest('test'); would alert 'changed' but instead it alerts 'unchanged'.
(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) - 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
Closures is your answer
(function($) {
var staticVariable = '';
$.widget('ui.newWidget', {
options: {
},
_init: function() {
}
});
})(jQuery);
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屋!