How to pass arguments to addEventListener listener

2018-12-31 21:16发布

The situation is somewhat like-

var someVar = some_other_function();
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);

The problem is that the value of someVar is not visible inside the listener function of the addEventListener, where it is probably being treated as a new variable.

23条回答
低头抚发
2楼-- · 2018-12-31 22:10

Also try these (IE8 + Chrome. I dont know for FF):

function addEvent(obj, type, fn) {
    eval('obj.on'+type+'=fn');
}

function removeEvent(obj, type) {
    eval('obj.on'+type+'=null');
}

// Use :

function someFunction (someArg) {alert(someArg);}

var object=document.getElementById('somObject_id') ;
var someArg="Hi there !";
var func=function(){someFunction (someArg)};

// mouseover is inactive
addEvent (object, 'mouseover', func);
// mouseover is now active
addEvent (object, 'mouseover');
// mouseover is inactive

Hope there is no typos :-)

查看更多
若你有天会懂
3楼-- · 2018-12-31 22:10

Function.prototype.bind() is the way to bind a target function to a particular scope and optionally define the this object within the target function.

someObj.addEventListener("click", some_function.bind(this), false);

Or to capture some of the lexical scope, for example in a loop:

someObj.addEventListener("click", some_function.bind(this, arg1, arg2), false);

Finally, if the this parameter is not needed within the target function:

someObj.addEventListener("click", some_function.bind(null, arg1, arg2), false);
查看更多
孤独总比滥情好
4楼-- · 2018-12-31 22:11

The following approach worked well for me. Modified from here.

function callback(theVar) {
  return function() {
    theVar();
  }
}

function some_other_function() {
  document.body.innerHTML += "made it.";
}

var someVar = some_other_function;
document.getElementById('button').addEventListener('click', callback(someVar));
<!DOCTYPE html>
<html>
  <body>
    <button type="button" id="button">Click Me!</button>
  </body>
</html>

查看更多
闭嘴吧你
5楼-- · 2018-12-31 22:15

There is a special variable inside all functions: arguments. You can pass your parameters as anonymous parameters and access them (by order) through the arguments variable.

Example:

var someVar = some_other_function();
someObj.addEventListener("click", function(someVar){
    some_function(arguments[0]);
}, false);
查看更多
弹指情弦暗扣
6楼-- · 2018-12-31 22:16

One way is doing this with an outer function:

elem.addEventListener('click', (function(numCopy) {
  return function() {
    alert(numCopy)
  };
})(num));

This method of wrapping an anonymous function in parentheses and calling it right away is called an IIFE (Immediately-Invoked Function Expression)

You can check an example with two parameters in http://codepen.io/froucher/pen/BoWwgz.

catimg.addEventListener('click', (function(c, i){
  return function() {
    c.meows++;
    i.textContent = c.name + '\'s meows are: ' + c.meows;
  }
})(cat, catmeows));
查看更多
登录 后发表回答