Hi.

snapper:
> How can I get object reference instead of window reference in
> this.handleEvent(evt)?
> 
> I have ECMAScript in a Batik SVG application using widgets. I noticed that
> the Carto textbox does not work in Batik due to event handing problems, so I
> am rewriting it. Andreas attached event handlers using the root element in
> all cases, which causes many problems. I am attaching events to the widget
> elements instead like this:
> 
> this.textboxRect.addEventListener("click",this._handleEvent,false);
> 
> The event handler in the textbox object does receive the event, but inside
> the this.handleEvent(evt), the "this" refers to the window object. We really
> want the reference to the textbox object.
> 
> How can I get the reference to the textbox object inside the event handler
> in this case?

This is normal behaviour: when you refer to this._handleEvent, it is
just a reference the function that has been stored in the 'this'
object–it has lost its association with the object.  If you want to be
able to access the 'this' object from _handleEvent, you can refer to
the object from the closure when you assign it.  For example:

  blah._handleEvent = function(evt) {
      // refer to 'blah' in here
  };

I often use a function to bind the the 'this' variable to an object of
my choosing, so that I can do what you want to do.

  function bind(_this, f) {
      var _ = function() {
          return f.apply(_this, arguments);
      };
      _.toString = function() {
          return "/* bound function */\n" + String(f);
      };
      return _;
  }

and then:

  blah._handleEvent = bind(blah, function() {
      // now 'this' inside here will always refer to 'blah',
      // regardless of how the function was called.
  });

-- 
Cameron McCormack, http://mcc.id.au/
        xmpp:[EMAIL PROTECTED]  ▪  ICQ 26955922  ▪  MSN [EMAIL PROTECTED]

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to