01.01.2015 Views

build_your_own_angularjs_sample

build_your_own_angularjs_sample

build_your_own_angularjs_sample

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Build Your Own Angular Chapter 1. Scopes And Digest<br />

it("executes $evalAsynced functions added by watch functions", function() {<br />

scope.aValue = [1, 2, 3];<br />

scope.asyncEvaluated = false;<br />

scope.$watch(<br />

function(scope) {<br />

if (!scope.asyncEvaluated) {<br />

scope.$evalAsync(function(scope) {<br />

scope.asyncEvaluated = true;<br />

});<br />

}<br />

return scope.aValue;<br />

},<br />

function(newValue, oldValue, scope) { }<br />

);<br />

scope.$digest();<br />

expect(scope.asyncEvaluated).toBe(true);<br />

});<br />

So what’s the problem As we have seen, we keep running the digest loop as long as<br />

there is at least one watch that is dirty. In the test case above, this is the case in the first<br />

iteration, when we first return scope.aValue from the watch function. That causes the<br />

digest to go into the next iteration, during which it also runs the function we scheduled<br />

using $evalAsync. But what if we schedule an $evalAsync when no watch is actually<br />

dirty<br />

test/scope_spec.js<br />

it("executes $evalAsynced functions even when not dirty", function() {<br />

scope.aValue = [1, 2, 3];<br />

scope.asyncEvaluatedTimes = 0;<br />

scope.$watch(<br />

function(scope) {<br />

if (scope.asyncEvaluatedTimes < 2) {<br />

scope.$evalAsync(function(scope) {<br />

scope.asyncEvaluatedTimes++;<br />

});<br />

}<br />

return scope.aValue;<br />

},<br />

function(newValue, oldValue, scope) { }<br />

);<br />

scope.$digest();<br />

expect(scope.asyncEvaluatedTimes).toBe(2);<br />

});<br />

30 ©2014 Tero Parviainen Errata / Submit

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!