From 453d4365d3226547a176fb410ff87de09bdd1aea Mon Sep 17 00:00:00 2001 From: Stefan Zermatten Date: Mon, 29 Jun 2015 09:41:01 +0200 Subject: [PATCH] Prevent memoized values being used in dependency loops --- rpg-docs/lib/memoize/memoize.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/rpg-docs/lib/memoize/memoize.js b/rpg-docs/lib/memoize/memoize.js index 092a4036..0b98d376 100644 --- a/rpg-docs/lib/memoize/memoize.js +++ b/rpg-docs/lib/memoize/memoize.js @@ -15,6 +15,7 @@ function CacheObject(func, address, args, cache, context){ var self = this; self.currentValue = null; self.dep = new Tracker.Dependency(); + self.numRun = 0; //spawn a new autorun that keeps the value up-to-date Tracker.nonreactive(function() { @@ -26,8 +27,22 @@ function CacheObject(func, address, args, cache, context){ delete cache[address]; return; } + //if we haven't run this before this flush, reset the counter after the flush + if(self.numRun === 0){ + Tracker.afterFlush(function(){ + self.numRun = 0; + }); + } + self.numRun++; //call the expensive function + //even if we don't use its value, we need to track its dependencies var newValue = func.apply(context, args); + //prevent dependency loops, the memoized function shouldn't re-run + //more than once per flush + if (self.numRun > 1){ + newValue = NaN; + if(_.isNaN(self.currentValue)) return; + } //if the value changed, store the new value if (self.currentValue !== newValue){ self.currentValue = newValue;