Best practice

If you did any development in AngularJS, I’m sure you know about the $watch function. On every digest cycle, Angular will evaluate an expression to see if its value changes. If it did, it will fire all the listeners on that particular watch.

Of course, this can be very expensive as your app grows and can cause serious performance issues. It is strongly recommended to unbind these watches when they are no longer needed. Usually this is when the current scope is destroyed. Luckily, all Angular scopes fire a $destroy event that can be used to perform the clean up.

Your code might look like this.

That’s how I did it, it does the job. But recently I found a very useful way of handling this in a better way. Simply wrap your watch as a $destroy event handler. This way you never have to worry about missed event callbacks again.

First time I saw this pattern was this gist.

Related posts

Comments are closed.