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

时间:2013-01-19 15:06:41

标签: javascript jquery

我正在尝试在下面的代码中使用watch.js。这个想法是以一次性方式运行watch.js,因此它检测到布尔变化(vars.in_animation)然后取消并退出。然而,发生的事情是代码陷入无限循环,每次vars.in_animation都会改变触发监视回调并且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); }               
     } 

编辑,只是提出了问题> 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";

1 个答案:

答案 0 :(得分:2)

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);
});