Reputation: 10632
I'm trying to use watch.js in the code below. The idea is too run watch.js in a one shot way, so it detects the boolean change (of vars.in_animation) and then unwatchs and exits. However, what happens is the code falls into inifinite loop and everytime vars.in_animation changes the watch callback is triggered and the unwatch code never runs.
I don't know whether the problem is the way I'm using watch.js, or if there is some other issue in the structure of the code. Any ideas?
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 made 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";
Upvotes: 0
Views: 234
Reputation: 664385
unwatch
seems to expect the watcher callback that should be removed as its third argument. Try
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);
});
Upvotes: 2