четверг, 23 октября 2014 г.

Creating AngularJS "watcher" factory in coffeescript

Recently I had to write a service that awaits some event, sent in rootScope. My goal was to make a kind of "watcher", which is created at the start of the application and do some work at the event.

First lets make angular module that creates a coffee class for our factory:

As you can see we inject $rootScope in our DataLoggingWatcher class instance. This class will be created only once (when we require DataLoggingWatcher)
And our class implementation is:

In constructor we save $rootScope for future use (adding @ symbol to parameter). After that we adding callback on 'newData' event. For testing purposes just simply write message to log.
To make it work - we require DataLoggingWatcher in our main controller:
 
And final part: how to test our watcher? Simple test looks like this:

We inject $rootScope in beforeEach to broadcast our event in test. After that we spy on function call and expect, that method logToConsole will be called on event.
And one more: to successfully spy on logToConsole method of our class we need to modify constructor:

So we call our logToConsole inside anonymous function because in that case will be called logToConsole method of instance DataLoggingWatche, not form class itself (and we can spy on it). 
Thats it. Full Gist