简体   繁体   中英

Catch response from callback-function or pass variable into callback function?

Using the facebook api, you can add a listener that triggers a function whenever someone clicks a like button:

FB.Event.subscribe('edge.create', page_like_callback);

This is what my function looks like, where I listen:

function($scope, $window) {
  $scope.liking = $window.liking;
  FB.Event.subscribe('edge.create', page_like_callback);
}

I want to set $scope.liking = true ; for whenever someone clicks like:

var page_like_callback = function(url, html_element) {
    $scope.liking = true;
};

But the $scope variable isn't accessible inside the callback. I either want to pass $scope to the callback or get a return from the callback and use that to set the like. What's the best approach for this and how should I do it?

You could have a function return your callback taking $scope as an argument so that $scope is now captured by the callback function

var page_like_callback = function($scope) {
    return function(url, html_element) {
        $scope.liking = true;
    };
}

FB.Event.subscribe('edge.create', page_like_callback($scope));

That's because the $scope variable is only defined within your function($scope, $window), so you need to make sure that page_like_callback has access to it. One way to do this is:

function($scope, $window) {
  var page_like_callback = function(url, html_element) {
    $scope.liking = true;
  };

  $scope.liking = $window.liking;
  FB.Event.subscribe('edge.create', page_like_callback);
}

That way, page_like_scope has access to $scope.

This is a bit spaghetti-ish, so you might need to provide more of your code if you want a better solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM