Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript `bind` method does not work as expected

The following controller works without problem.

 app.controller('foo', ['$scope',function ($scope) {
        $scope.delete = function(){
            bar($scope);
         }
    }]);

I tried to make it a little cleaner by using bind:

 app.controller('foo', ['$scope',function ($scope) {
        $scope.delete = bar.bind(null, $scope);
    }]);

Unfortunately, this form does not work as expected and $scope is always supplied with an old version of $scope in bound method (bar here), even after $scope has changed to refer to a different value. What is wrong with it?

What else?

If I should not use bind here, what is the alternative?

like image 926
Handsome Nerd Avatar asked Jun 09 '15 12:06

Handsome Nerd


1 Answers

I assume that your problem is that your bound Util.bar is always supplied with an old version of $scope, even after $scope has changed to refer to a different value.

bind binds values, not variables. You are binding the current value of $scope to Util.bar. On the other hand, your first style forces the identifier $scope to be resolved to a value (or, really, outer-scope variable record) every time the function runs.

If $scope changes to refer to a completely different value, you must use the first form. .bind(null, $scope) will resolve $scope to a value immediately and use that value forever, while the first form without bind will resolve $scope to a value every time the function runs.

like image 130
apsillers Avatar answered Sep 27 '22 21:09

apsillers