One-time events for your scopes!
In the previous post, we created a simple service called deregister
to make event listeners deregistration easier. But sometimes you don’t even need to listen to an event more than once, and then the deregistration task is boring. No more!
Got the data? Move on, soldier.
Sometimes, you just want to listen to an event, but just one time. Your code usually ends up like this:
1 | function ($rootScope) { |
This is boring. jQuery’s got .one
for this kind of stuff (even jqLite does!). Why didn’t they implement Scope.$one
, man I will never now. But thanks to AngularJS 1.4 decorators, we can fix this!
Enter Scope.$one
Turns out it’s quite easy to implement Scope.$one
by decorating the $rootScope
service. The Scope
class itself isn’t exposed so we can’t alter its prototype, but we can add a hook to the $rootScope.$new
method (which is used to create every single scope in the application) to inject our $one
method afterwards.
1 | angular |
Conclusion
Now we can update our original use case:
1 | function ($rootScope) { |
Sidenotes
Note that this tip doesn’t exempt you from deregistering manually if the event is never fired. Using our deregister
service, the example looks like this:
1 | function ($rootScope, deregister) { |