我正在尝试在下面的代码中使用watch.js。这个想法太单次运行 watch.js,所以它检测到布尔变化(vars.in_animation),然后取消观察并退出。但是,发生的情况是代码陷入无限循环,并且每次 vars.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); }
}
编辑,只是解决了问题> 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";