build_your_own_angularjs_sample
build_your_own_angularjs_sample
build_your_own_angularjs_sample
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Build Your Own Angular Chapter 1. Scopes And Digest<br />
want to prevent unnecessary rendering: Why let the browser render DOM changes that are<br />
going to be immediately overridden anyway<br />
Here’s the contract of $evalAsync expressed as a unit test:<br />
test/scope_spec.js<br />
it("executes $evalAsynced function later in the same cycle", function() {<br />
scope.aValue = [1, 2, 3];<br />
scope.asyncEvaluated = false;<br />
scope.asyncEvaluatedImmediately = false;<br />
});<br />
scope.$watch(<br />
function(scope) { return scope.aValue; },<br />
function(newValue, oldValue, scope) {<br />
scope.$evalAsync(function(scope) {<br />
scope.asyncEvaluated = true;<br />
});<br />
scope.asyncEvaluatedImmediately = scope.asyncEvaluated;<br />
}<br />
);<br />
scope.$digest();<br />
expect(scope.asyncEvaluated).toBe(true);<br />
expect(scope.asyncEvaluatedImmediately).toBe(false);<br />
We call $evalAsync in the watcher’s listener function, and then check that the function<br />
was executed during the same digest, but after the listener function had finished executing.<br />
The first thing we need is a way to store the $evalAsync jobs that have been scheduled.<br />
We can do this with an array, which we initialize in the Scope constructor:<br />
src/scope.js<br />
function Scope() {<br />
this.$$watchers = [];<br />
this.$$lastDirtyWatch = null;<br />
this.$$asyncQueue = [];<br />
}<br />
Let’s next define $evalAsync, so that it adds the function to execute on this queue:<br />
src/scope.js<br />
Scope.prototype.$evalAsync = function(expr) {<br />
this.$$asyncQueue.push({scope: this, expression: expr});<br />
};<br />
28 ©2014 Tero Parviainen Errata / Submit