我正在尝试使用 watch.js在下面的代码中。这个想法也是以一次性方式运行 watch.js,因此它会检测(vars.in_animation 的) bool 值变化,然后取消监视并退出。然而,发生的情况是代码陷入无限循环,每次 vars.in_animation 更改时,都会触发监视回调,并且取消监视代码永远不会运行。
我不知道问题是否出在我使用 watch.js 的方式上,或者代码结构中是否存在其他问题。有什么想法吗?
base.goTo = function(targetSlide){
if (vars.in_animation || !api.options.slideshow)
{
//arrange for a callback once in_animation is false again
//only need to detect first change from true to false, and then unwatch
watch(vars, "in_animation", function()
{
console.log('called back, value of in_animation ' + vars.in_animation);
unwatch(vars,"in_animation",vars.alert); //never called
base.goTo2(vars.saved_slide);
});
vars.saved_slide = targetSlide;
return false;
}
else { base.goTo2(targetSlide); }
}
编辑,刚刚解决了问题> http://jsfiddle.net/SZ2Ut/3/
var obj = {
name: "buddy",
alert: function(){
alert(obj.phrase + " " + obj.name);
}
}
watch(obj, "name", function(){
alert('name has changed to: ' + obj.name);
});
//should only fire once for this one
obj.name = "johnny";
unwatch(obj, "name", obj.alert);
obj.name = "phil";
最佳答案
unwatch
似乎期望观察者回调应该作为其第三个参数被删除。尝试一下
watch(vars, "in_animation", function callback() {
console.log('called back, value of in_animation ' + vars.in_animation);
unwatch(vars,"in_animation", callback);
base.goTo2(vars.saved_slide);
});
关于javascript - 使用 watch.js 取消监视对象时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14415654/