16.07.2017 Views

AngularJS Essentials

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

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

Chapter 5<br />

When invoked, this function dispatches an event to all of its registered child scopes.<br />

In order to receive and handle the desired broadcast, $scope needs to call the $on<br />

function, thus informing you of the events you want to receive and also the functions<br />

that will be handling it.<br />

For this implementation, we are going to send the broadcast through the $rootScope<br />

object, which means that the broadcast will affect the entire application.<br />

In the following code, we created a service called TickGenerator. It informs<br />

the current date every second, thus sending a broadcast to all of its children<br />

(the services.js file):<br />

parking.factory("tickGenerator", function($rootScope, $timeout) {<br />

var _tickTimeout;<br />

var _start = function () {<br />

_tick();<br />

};<br />

var _tick = function () {<br />

$rootScope.$broadcast("TICK", new Date());<br />

_tickTimeout = $timeout(_tick, 1000);<br />

};<br />

var _stop = function () {<br />

$timeout.cancel(_tickTimeout);<br />

};<br />

var _listenToStop = function () {<br />

$rootScope.$on("STOP_TICK", function (event, data) {<br />

_stop();<br />

});<br />

};<br />

_listenToStop();<br />

return {<br />

start: _start,<br />

stop: _stop<br />

};<br />

});<br />

[ 111 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!