AngularJS是否具有本机延迟$ rootScope。$ apply?

时间:2013-06-02 02:47:03

标签: javascript angularjs

我正在编写很多看起来像这样的代码:

obj.bind( 'event', function(){
    $rootScope.$apply( function(){
        somePromise.resolve();
        doSomething();
    }
} );

我想把它压缩成类似于:

的东西
obj.bind( 'event', deferRootScopeApply( function(){
    somePromise.resolve();
    doSomething();
} );

写一个能做到这一点的服务很容易,但我只是想知道是否有一种更清洁的本地方式。

1 个答案:

答案 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 );