默认情况下,我无法将参数传递给回调函数
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>
答案 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>