Last active
June 16, 2016 14:23
-
-
Save timgit/cde797019d4694511ac5 to your computer and use it in GitHub Desktop.
Angular message bus and smartWatch
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('rootScopeExtensionsModule', []) | |
.config($provide => { | |
$provide.decorator('$rootScope', $delegate => { | |
var rootScope = $delegate; | |
Object.defineProperty(rootScope.constructor.prototype, '$bus', { | |
get: function() { | |
return { | |
publish: (msg, data) => { | |
// emit goes to parents, broadcast goes down to children | |
// since rootScope has no parents, this is the least noisy approach | |
// however, with the caveat mentioned below | |
rootScope.$emit(msg, data); | |
}, | |
subscribe: (msg, func) => { | |
// ignore the event. Just want the data | |
var unbind = rootScope.$on(msg, (event, data) => func(data)); | |
// being able to enforce unbinding here is why decorating rootscope | |
// is preferred over DI of an explicit bus service | |
this.$on('$destroy', unbind); | |
} | |
}; | |
} | |
}); | |
Object.defineProperty(rootScope.constructor.prototype, '$smartWatch', { | |
get: function() { | |
return (expression, handler) => { | |
return this.$watch(expression, (newValue, oldValue) => { | |
if (oldValue !== newValue) | |
handler(); | |
}, true); | |
}; | |
} | |
}); | |
return rootScope; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment