Last active
August 29, 2015 14:05
-
-
Save zefei/8a18059ecceebee45bee to your computer and use it in GitHub Desktop.
Using Angular and Meteor together: reactive wrapper
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
// bind a Meteor reactive computation to the current scope | |
angular.module('myApp') | |
.factory('autorun', function() { | |
return function(scope, fn) { | |
// wrapping around Deps.autorun | |
var comp = Deps.autorun(function(c) { | |
fn(c); | |
// this is run immediately for the first call | |
// but after that, we need to $apply to start Angular digest | |
if (!c.firstRun) setTimeout(function() { | |
// wrap $apply in setTimeout to avoid conflict with | |
// other digest cycles | |
scope.$apply(); | |
}, 0); | |
}); | |
// stop autorun when scope is destroyed | |
scope.$on('$destroy', function() { | |
comp.stop(); | |
}); | |
// return autorun object so that it can be stopped manually | |
return comp; | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment