Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to reference a function from Javascript class method?
    text
    copied!<p>I use SWFAddress for deep linking my site (<a href="http://www.asual.com/swfaddress/" rel="nofollow">link to SWFAddress</a>). I like to break code into classes so I have a main structure similar to this:</p> <pre><code>function SomeClass() { //this adds the this.handleChange() function to the //SWFAddress event listener this.initializeSWFA = function() { //SWFAddress variable is instantiated in SWFAddress javascript file //so I can use it here SWFAddress.addEventListener(SWFAddressEvent.CHANGE, this.handleChange); } //SWFAddress suppose to call this function this.handleChange= function(evt) { //some code here } } //instantiate the SomeClass var someVar = new SomeClass(); someVar.initializeSWFA(); </code></pre> <p>This line does not work here:</p> <pre><code>SWFAddress.addEventListener(SWFAddressEvent.CHANGE, this.handleChange); </code></pre> <p>I tried changing it to:</p> <pre><code>SWFAddress.addEventListener(SWFAddressEvent.CHANGE, this.handleChange()); </code></pre> <p>or</p> <pre><code>var self = this; SWFAddress.addEventListener(SWFAddressEvent.CHANGE, self.handleChange); </code></pre> <p>and these don't work either.</p> <p>So how to reference a javascript function from a class in situation like this? If the function <code>handleChange</code> would be outside of the class I can write the function's name.</p> <p>Thank you in advance</p> <p><strong>EDIT</strong></p> <p>First, thank you for all the answers. I am still trying to figure how this all works in Javascript. I am not used to the object oriented model like here in Javascript.</p> <p>This is the solution for now. I still can't figure out how to do this nicely in Javascript but this solution works. I tried to implement the solution suggested by ehudokai (thank you) however was not able to make it work.</p> <pre><code>function SomeClass() { //this adds the this.handleChange() function to the //SWFAddress event listener this.initializeSWFA = function() { //SWFAddress variable is instantiated in SWFAddress javascript file //so I can use it here SWFAddress.addEventListener(SWFAddressEvent.CHANGE, someFunc); } //SWFAddress suppose to call this function this.handleChange= function(evt) { //some code here } } //instantiate the SomeClass var someVar = new SomeClass(); function someFunc(evt) { someVar.handleChange(evt); } someVar.initializeSWFA(); </code></pre> <p>I don't like this because this involves defining one extra function, so takes extra space If anybody figures out how to add a method to SWFAddress EventListener from a Javascript object, please help me out.</p>
 

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