Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your problem is with this line: <code>$('#some-element').click(this.doSomething);</code></p> <h3>Why this is a problem</h3> <p>JavaScript methods don't know anything about the object that should be assigned to <code>this</code>, it's set when the method is called either explicitly (with <code>myFunction.call(obj)</code>) or implicitly (when called using <code>obj.myFunction()</code>).</p> <p>For example:</p> <pre><code>var x = { logThis: function () { console.log(this); } }; x.logThis(); // logs x x.logThis.call(y); // logs y var func = x.logThis; func(); // logs window: the fallback for when no value is given for `this` </code></pre> <p>In your case, you're passing <code>this.doSomething</code> to jQuery, which is then explicitly calling it with the element that was clicked as the value of <code>this</code>. What's happening is (a slightly more complex version of) this:</p> <pre><code>var callback = this.doSomething; callback.call(anElement, anEvent); </code></pre> <h3>The solution</h3> <p>You need to make sure that <code>doSomething</code> is called with the right value of <code>this</code>. You can do that by wrapping it in another function:</p> <pre><code>var cb = this; $('#some-element').click(function() { return cb.doSomething(); }); </code></pre> <p>jQuery provides a <a href="http://api.jquery.com/jQuery.proxy/" rel="noreferrer"><code>proxy</code></a> function lets you do this more simply:</p> <pre><code>$('#some-element').click(jQuery.proxy(this.doSomething, this)); </code></pre>
    singulars
    1. This table or related slice is empty.
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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