Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

this inside addeventlistener callback

The 'this' inside an addeventlistener callback is always null and I think this is not a nice thing.
Such way I can't do pass as callback an custom object method ad referencing that object inside the method..

for example I can't do

customObject = {
var1: 1,
callbackmetod: function(e){alert(this.var1)} 

titaniumObject.addEventListener('click', customObject.callbackmetod)
— asked October 11th 2010 by Fabiano Taioli
  • addeventlistener
  • callback
  • class
  • this

1 Answer

  • Accepted Answer

    You can store your object within the object that is being clicked and then access it within the click event itself. Here's an example.

    var customObject = {
    var1: 1,
    callbackmetod: function(e){
    titaniumObject.myobject = customObject;
    titaniumObject.addEventListener('click', customObject.callbackmetod);

    BTW - e.source will be titaniumObject in this example because it is the source of the event and objects in Titanium can be assigned custom properties safely.

    — answered October 11th 2010 by John McKnight
    • Thank you for you reply, Yes this solution can work but it's not very smart. Think if I have many custom object, i have to store one by one in separate variables of the titaniumObject. Is there an intrinsic reason for have 'this' null inside the callback?

      — commented October 11th 2010 by Fabiano Taioli
    • What scenario would have one titaniumObject with many events attached? Yes, I agree it isn't an elegant solution but it is one way.

      — commented October 11th 2010 by John McKnight
    • Ok, I think I will follow the method proposed by you for the moment. Hope in future a reference to the owner javascript object will be available inside the callback method.
      Thank you very much for your time.

      — commented October 12th 2010 by Fabiano Taioli
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.