将参数传递给回调函数

时间:2016-01-26 09:10:54

标签: javascript node.js

默认情况下,我无法将参数传递给回调函数

function callback() {
  alert('Hi human');
}
var x = 1, y = 2;//Pass arguments(x,y) to a callback function
document.getElementById('someelem').addEventListener('click', callback);
<button id="someelem">Ok</button>

3 个答案:

答案 0 :(得分:3)

document.getElementById('someelem').addEventListener('click', function(event) {
    callback(x, y, e);
});

另一种方法是bind功能

document.getElementById('someelem').addEventListener('click', callback.bind(null, x, y));

答案 1 :(得分:2)

您可以将其创建为匿名函数,如下所示:

app.factory('requestService', ['$http', '$q', function($http, $q, requestService) {

    var urls = {
        'getNews': '/Api/News/GetNews?pageNumber=%pageNumber%'
    };

    return {        
        getNews: function(pageNumber) {
            var requestUrl = urls['getNews'].replace('%pageNumber%', $pageNumber);
            var defer = $q.defer()
            $http({ 
                method: 'GET', 
                url: requestUrl
            }).then(function(response) {
                defer.resolve(response.data);
            }, function() {
                defer.reject('Some meaningful message');
            });
            return defer.promise;
        }
    }
}]);

答案 2 :(得分:0)

您可以使用bind来解决问题。

function callback(x, y) {
  console.log(this,x,y);
}
var x = 1,
  y = 2; //Pass arguments(x,y) to a callback function
var el = document.getElementById('someelem');
el.addEventListener('click', callback.bind(el, x, y));
<button id="someelem">OK</button>