I have a custom library in my Titanium Mobile (3.1.0 GA SDK) project that looks something like this:
// lib/MyObject.js
function MyObject
{
var self = this;
_.extend(self, Backbone.Events);
this.trigger('myEvent');
}
module.exports = MyObject;
In another part of my application, I make the class available globally:
Alloy.Globals.MyObject = require('MyObject');
And in a controller, I instantiate it:
var myObj = new Alloy.Globals.MyObject();
That object gets passed around a bit, until finally an event listener is added:
// In another controller
myObj.on('myEvent', function() {
console.log('My event happened!');
};
Unfortunately, log command never gets called. If I add an event listener within the MyObject function, it works fine. But it won't work when called from outside the object.
I would just assume that there's a bug in there, or the object is getting passed by value instead of reference, except for this. If I change the class definition to the following:
// lib/MyObject.js
function MyObject
{
var self = this;
_.extend(self, Backbone.Events);
var old_on = this.on;
this.on = function(a, b, c) {
return old_on.call(self, a, b, c);
};
this.trigger('myEvent');
}
module.exports = MyObject;
...everything works. Somehow the on
function is not getting the correct context, but I can't for the life of me figure out why. Anyone have insight into what's going on?