Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

javascript - 监听JavaScript中的变量更改(Listening for variable changes in JavaScript)

Is it possible to have an event in JS that fires when the value of a certain variable changes?(某个变量的值更改时,是否可能在JS中触发事件?)

JQuery is accepted.(接受JQuery。)   ask by rashcroft22 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, this is now completely possible!(是的,现在完全有可能!)

I know this is an old thread but now this effect is possible using accessors (getters and setters): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters(我知道这是一个旧线程,但是现在可以使用访问器(获取器和设置器)实现这种效果: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters) You can define an object like this, in which aInternal represents the field a :(您可以定义一个这样的对象,其中aInternal表示字段a :) x = { aInternal: 10, aListener: function(val) {}, set a(val) { this.aInternal = val; this.aListener(val); }, get a() { return this.aInternal; }, registerListener: function(listener) { this.aListener = listener; } } Then you can register a listener using the following:(然后,您可以使用以下方法注册侦听器:) x.registerListener(function(val) { alert("Someone changed the value of x.a to " + val); }); So whenever anything changes the value of xa , the listener function will be fired.(因此,只要有什么改变xa的值,就会触发监听器函数。) Running the following line will bring the alert popup:(运行以下行将弹出警报弹出窗口:) x.a = 42; See an example here: https://jsfiddle.net/5o1wf1bn/1/(在此处查看示例: https//jsfiddle.net/5o1wf1bn/1/) You can also user an array of listeners instead of a single listener slot, but I wanted to give you the simplest possible example.(您还可以使用一组侦听器而不是一个侦听器插槽,但是我想给您提供最简单的示例。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...