puiu91
11/21/2015 - 12:43 AM

Javascript add event listener methods

Javascript add event listener methods

http://stackoverflow.com/questions/256754/how-to-pass-arguments-to-addeventlistener-listener-function

// method 1 - anonymous function that calls the actual function and passes the necessary parameter
deleteUnitButton.addEventListener('click', function() {
  deleteUnit(rowIndex)
}, false);



// method 2 - add the variable to the object that has an event listener attached (prototypical langauge advantage)
var someInput = document.querySelector('input');

someInput.myParam = 'This is my parameter';
someInput.addEventListener('click', myFunc, false);

function myFunc(event) {
  window.alert( event.target.myParam );
}



// method 2.1 - the same, but using an anonymous function instead of a named function expression
var someInput = document.querySelector('input');

someInput.myParam = 'This is my parameter';
someInput.addEventListener('click', myFunc() {
  window.alert( event.target.myParam );
}, false);



// method 3 - using bind to instead of an anonymous wrapper
function someFunction(otherFunc, ev) {
    // magic happens
}
someObj.addEventListener('click', someFunction.bind(null, someOtherFunction), false);



// method 4 - internal return function using an outer function to pass someVar to the anonymous function
//            where theVar = someVar
var someVar = some_other_function()
        
someObj.addEventListener('click', function(theVar) {
  return function() {
    some_function(theVar)
  }
}(someVar), false)

// passing two parameters
catimg.addEventListener('click', (function(c, i) {
  return function() {
    c.meows++;
    i.textContent = c.name + '\'s meows are: ' + c.meows;
  }
})( cat, catmeows ));


// alternate 1
myaudio.addEventListener('ended', funcName = function() {
  newSrc(myaudio)
}, false)

// alternate 2
someObj.addEventListener('click', function() { 
    some_function(someVar); 
  }.bind(this)
);

// alternate 3
root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));
http://passy.svbtle.com/partial-application-in-javascript-using-bind