I'm writing a lot of code that looks like this:
obj.bind( 'event', function(){
$rootScope.$apply( function(){
somePromise.resolve();
doSomething();
}
} );
I'd like to compress it to something akin to:
obj.bind( 'event', deferRootScopeApply( function(){
somePromise.resolve();
doSomething();
} );
It's easy enough to write a service that does this, but I'm just wondering if there's a cleaner native way.
FWIW, this is my service:
app.factory( 'rootApply', [ '$rootScope', function( $rootScope ){
return function( fn, scope ){
var args = [].slice.call( arguments, 1 );
// push null as scope if necessary
args.length || args.push( null );
return function(){
// binds to the scope and any arguments
var callFn = fn.bind.apply(
fn
, args.slice().concat( [].slice.call( arguments ) )
);
// prevent applying/digesting twice
$rootScope.$$phase
? callFn()
: $rootScope.$apply( callFn )
;
}
};
} ] );
which then returns a deferred function or optionally acts like fn.call:
rootApply( someFunction );
rootApply( someFunction, scope, arg1, arg2, arg3 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With