Created
June 2, 2015 18:51
-
-
Save mgwidmann/a4b1a7d2ee6bcc2ef6bb to your computer and use it in GitHub Desktop.
Angular watcher hiding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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