侦听JavaScript中的变量更改是否有可能在JS中有一个事件在某个变量的值发生变化时触发?接受jQuery。
3 回答
千巷猫影
TA贡献1829条经验 获得超7个赞
var myobj = {a : 1};function create_gets_sets(obj) { // make this a framework/global function var proxy = {} for ( var i in obj ) { if (obj.hasOwnProperty(i)) { var k = i; proxy["set_"+i] = function (val) { this[k] = val; }; proxy["get_"+i] = function () { return this[k]; }; } } for (var i in proxy) { if (proxy.hasOwnProperty(i)) { obj[i] = proxy[i]; } }}create_gets_sets(myobj);
function listen_to(obj, prop, handler) { var current_setter = obj["set_" + prop]; var old_val = obj["get_" + prop](); obj["set_" + prop] = function(val) { current_setter.apply(obj, [old_val, val]); handler(val));}
listen_to(myobj, "a", function(oldval, newval) { alert("old : " + oldval + " new : " + newval);}
function watch(obj, prop, handler) { // make this a framework/global function var currval = obj[prop]; function callback() { if (obj[prop] != currval) { var temp = currval; currval = obj[prop]; handler(temp, currval); } } return callback;}var myhandler = function (oldval, newval) { //do something};var intervalH = setInterval(watch(myobj, "a", myhandler), 100);myobj.set_a(2);
添加回答
举报
0/150
提交
取消