Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I pass a local variable from function to event listener function in JavaScript?
    primarykey
    data
    text
    <p>Good day!</p> <p>I began writing my own basic JavaScript library for personal use and distribution a few days ago, but I am having trouble with one of the methods, specifically <strong>bind()</strong>.</p> <p>Within the method itself, <strong>this</strong> refers to the library, the object.</p> <p>I went to Google and found <strong>function.call()</strong>, but it didn't work out the way I planned it--it just executed the function.</p> <p>If you take a look at another method, <strong>each()</strong>, you'll see that it uses <strong>call()</strong> to pass values.</p> <p>I also tried the following:</p> <pre><code>f.arguments[0]=this; </code></pre> <p>My console throws an error, saying it cannot read '0' of "undefined".</p> <p>I would like to be able to pass <strong>this</strong> (referencing the library--NOT THE WINDOW) to use it in the event listener.</p> <p>You can see it starting at line 195 of the JavaScript of <a href="http://jsfiddle.net/3fuab/" rel="nofollow">this JSFiddle</a>.</p> <p>Here it is as well:</p> <pre><code>bind:function(e,f){ if(e.indexOf("on")==0){ e=e.replace("on",""); } if(typeof f==='function'){ /*Right now, 'this' refers to the library How can I pass the library to the upcoming eventListener? */ //f=f(this); doesn't work //f.call(this); //doesn't work //this.target refers to the HTMLElement Object itself, which we are adding the eventListener to //the outcome I'm looking for is something like this: /*$('h3').which(0).bind(function({ this.css("color:red"); });*/ //(which() defines which H3 element we're dealing with //bind is to add an event listener this.target.addEventListener(e,f,false) } return this; }, </code></pre> <p>Thank you so much for your help, contributors!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload