Skip to content

Instantly share code, notes, and snippets.

@tincho
Last active November 22, 2018 20:17
Show Gist options
  • Save tincho/2075a9f131fd2b27057195b36246d2e0 to your computer and use it in GitHub Desktop.
Save tincho/2075a9f131fd2b27057195b36246d2e0 to your computer and use it in GitHub Desktop.
/**
* @license MIT
* @requires AngularJs 1.x
* @author github.com/tincho
* Tiny helper for listener deregistration on scope destroy
* You'll have to wrap it up in a module/provider/whatever
* (that's out of my focus)
*/
function LDisposer(scope) {
var _list = [];
function _exec(fn) { fn(); }
function addListener(listener) {
if (typeof listener !== "function") return;
_list.push(listener);
}
addListener.destroy = _list.forEach.bind(_list, _exec);
// fallback fake empty "scope" just to keep syntax the same
scope = scope || { $on: function(){} };
scope.$on('destroy', addListener.destroy);
// this is the public API:
return addListener;
}
// usage
//////////////
// option A // (, for Automatic) - need to pass $scope
//////////////
var l = new LDisposer($scope);
...
l($scope.$watch("a", function() { ... }));
l($scope.$watch("b", function() { ... }));
l($scope.$on("c", function() { ... }));
// that's it. add your watchs and forget about them
//////////////
// option B // (not providing scope)
//////////////
var l = new LDisposer();
l($scope.$watch("a", function() { ... }));
l($scope.$watch("b", function() { ... }));
l($scope.$watch("c", function() { ... }));
// but with this way dont forget to:
$scope.$on('$destroy', l.destroy);
// !!!!!!!!!!!!!!!!!!!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment