使用watch.js取消监视对象的问题

Problems unwatching an object using watch.js

本文关键字:对象 问题 监视 取消 watch js 使用      更新时间:2023-09-26

我试图在下面的代码中使用watch.js。这个想法是以一种一次性的方式运行watch.js,所以它会检测到布尔值的变化(var .in_animation),然后取消监视并退出。然而,发生的是代码陷入无限循环和每次变量。In_animation改变了watch回调被触发,unwatch代码永远不会运行。

我不知道问题是我使用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); }               
     } 

EDIT, just make a fiddle of the problem> 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);
});