html - Add AND remove eventlistener with arguments and access element and event? - Javascript -


okay. understand there few ways manage events in javascript.

  1. inline, eg. <div id=myid onclick="alert('hi')"> - supposedly shouldn't it.
  2. event handlers, eg. element.onclick = new function("myfunc('args')"); - supposedly better not best
  3. event listeners, eg. element.addeventlistener("click",myfunc,false)-supposedly best way of doing things

so, lets want pass arguments function. hear should calling function within function this:

myelement.addeventlistener("click",function whatever(event){     myfunk(event,"some argument"); },false); 

but if want remove it?

myelement.removeeventlistener("click",whatever,false);

this returns "whatever not defined" error in console. function not have name? "whatever" not name? how remove it?

i need way assign event listener , pass arguments, , rid of later. how do this?

edit:

okay, yes, cannot refer whatever because written inline. reason forced use function expression inline because want pass arguments. want pass arguments because don't want have define new function every time want change behaviour. if use event handler (not 'listener') can swap out actions , still use parameters:

element.onclick("myfunc('do 1 thing')");

element.onclick("myfunc('do different thing')");

and using this, never have define new function, pass myfunc twice different parameters. how do addeventlistener?

for addeventlistener()'s second argument, this:

whatever= function(event) {   ... } 

… instead of this:

function whatever(event) {   ... } 

you'll able remove event this:

myelement.removeeventlistener('click' , whatever); 

to pass parameters event, use bind, this:

whatever= myfunk.bind(myelement, parameter1, parameter2, ...) 

example

var myelement= document.getelementbyid('myelement');    function myfunk(s) {    this.innerhtml+= '<br>'+s;    myelement.removeeventlistener('click', whatever);      myelement.addeventlistener(      'click',      whatever= myfunk.bind(myelement, 'clicked again.')    );  }    myelement.addeventlistener(    'click',    whatever= myfunk.bind(myelement, 'clicked once.')  );
<div id="myelement">click me!</div>


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -