Question

I've just wrote this function for answer on SO:

function ngWrap($scope, fn) {
    return function() {
        var args = [].slice.call(arguments);
        return $scope.$apply(function() {
            fn.apply(null, args);
        });
    };
}

With a better version:

function ngWrap($scope, fn) {
    return function() {
        var args = [].slice.call(arguments);
        if ($scope.$$phase) {
            fn.apply(null, args);
        } else {
            return $scope.$apply(function() {
                fn.apply(null, args);
            });
        }
    };
}

that can be use to shorten this:

socket.on('myevent', function(arg){$scope.$apply(function(){trigger_fn(arg)})})

into:

socket.on('myevent', ngWrap($scope, trigger_fn));

Does this function have a name (the first one) or maybe you can write simple version of it using underscore (that can use just $scope.$apply.bind($scope) as argument) or maybe lisp have a function that word that way?

Was it helpful?

Solution

Does this function have a name

Not that I know, but I could think of "lifting fn to the Angular $scope" or so.

you can write simple version of it using underscore

Yes, what you're doing there is basic function composition, so you can use Underscore's compose function:

function ngWrap($scope, fn) {
    return _.compose($scope.$apply.bind($scope), fn);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top