我正在编写很多看起来像这样的代码:
obj.bind( 'event', function(){
$rootScope.$apply( function(){
somePromise.resolve();
doSomething();
}
} );
我想把它压缩成类似于:
的东西obj.bind( 'event', deferRootScopeApply( function(){
somePromise.resolve();
doSomething();
} );
写一个能做到这一点的服务很容易,但我只是想知道是否有一种更清洁的本地方式。
答案 0 :(得分:3)
FWIW,这是我的服务:
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 )
;
}
};
} ] );
然后返回延迟函数或者可选择像fn.call
:
rootApply( someFunction );
rootApply( someFunction, scope, arg1, arg2, arg3 );