Skip to content

Instantly share code, notes, and snippets.

@mgwidmann
Created June 2, 2015 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgwidmann/a4b1a7d2ee6bcc2ef6bb to your computer and use it in GitHub Desktop.
Save mgwidmann/a4b1a7d2ee6bcc2ef6bb to your computer and use it in GitHub Desktop.
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