Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular watcher hiding
angular.module('utils.watcher_hider', [])
.service 'WatcherHider', ['$log', ($log)->
($scope)->
@scope = $scope
# Don't try this at home kids...
listeners = []
watches = []
@$watch = (name_or_fn, watcher_fn)=>
listener = @scope.$watch(name_or_fn, watcher_fn)
watches.push([name_or_fn, watcher_fn])
listeners.push(listener)
@hide = (name)=>
@scope.$on name, ()->
$log.debug "Unregistering watchers"
_.each listeners, (unregister)->
unregister()
listeners = []
@unhide = (name)=>
that = @
@scope.$on name, ()->
$log.debug "Reregistering watchers"
_.each watches, (watch_args)->
listeners.push that.scope.$watch.apply(that.scope, watch_args)
that.scope.$apply()
@
]
###
Then use in your scope like this:
angular.module('some.module', ['utils.watcher_hider'])
.controller 'SomeController', ['WatcherHider', '$scope', (WatcherHider, $scope)->
# Watches like this:
$scope.$watch ->
Compute.something(expensive)
, ->
console.log('some data changed')
# Can be replaced with:
hider = new WatcherHider($scope)
hider.$watch ->
Compute.something(expensive)
, ->
console.log('some data changed')
hider.hide('Some event name that is fired to indicate watchers should be hidden')
hider.unhide('Some event name that is fired to indicate watchers should be put back')
###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.