javascripthtmldom-events

How to pass parameter to function using in addEventListener?


In the traditional way to add event listener:

function getComboA(sel) {
    var value = sel.options[sel.selectedIndex].value;  
}

<select id="comboA" onchange="getComboA(this)">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>

But I wanted to adapt to the addEventListener way:

productLineSelect.addEventListener('change',getSelection(this),false);

function getSelection(sel){
    var value = sel.options[sel.selectedIndex].value;
    alert(value);
}

It doesn't work because I can't pass any parameter in getSelection() as the second parameter in addEventListener method? As far as I know I can only use the function name without parenthesises.

Any idea?

BTW, please look at my previous question about console.log doesn't work in Safari 6.0 Developer Inspector, I can't write any output in the console, which is frustrating.


Solution

  • No need to pass anything in. The function used for addEventListener will automatically have this bound to the current element. Simply use this in your function:

    productLineSelect.addEventListener('change', getSelection, false);
    
    function getSelection() {
        var value = this.options[this.selectedIndex].value;
        alert(value);
    }
    

    Here's the fiddle: http://jsfiddle.net/dJ4Wm/


    If you want to pass arbitrary data to the function, wrap it in your own anonymous function call:

    productLineSelect.addEventListener('change', function() {
        foo('bar');
    }, false);
    
    function foo(message) {
        alert(message);
    }
    

    Here's the fiddle: http://jsfiddle.net/t4Gun/


    If you want to set the value of this manually, you can use the call method to call the function:

    var self = this;
    productLineSelect.addEventListener('change', function() {
        getSelection.call(self);
        // This'll set the `this` value inside of `getSelection` to `self`
    }, false);
    
    function getSelection() {
        var value = this.options[this.selectedIndex].value;
        alert(value);
    }