JavaScript Event Handlers
JavaScript Event Handlers don't work the way that you may expect. For instance, if you had a component that defined an event itemCreated. That event could add an event handler through the "add_" method, as such:
add_itemCreated
You'd add an event handler through the process of something like this:
initialize : function() {
this._myComponent = new myComponent();
this._myComponent.add_itemCreated(this._itemCreatedCallback);
}
_itemCreatedCallback : function(sender, e) {
//handler
}
This event handler would be in the class definition of the component using the myComponent object reference. So myComponent has an itemCreated event that gets fired by something. When that event fires, the _itemCreatedCallback method is called. There are a couple of ways that events can be defined though; I defined it above in a JavaScript component, but the other process can occur in the $create statement, which happens whenever the ScriptDescriptor describes the component. The $create statement takes a collection of events by event name. Internally, a collection of events store the name of the method to call to add the event handler, using the "add_itemCreated" method name as the key.
You may think that to reference the component you can use the this keyword in this instance; but the "this" keyword doesn't reference the component instance that has the _itemCreatedCallback; instead, the this keyword references the definition of the method, which makes it challenging because I've personally needed to be able to reference the component. The way around that may be to pass in a reference of the component somehow as a property of the event argument associated with the event.
A better way is to create a delegate using the Function.createDelegate method. The new approach would be:
initialize : function() {
this._myComponent = new myComponent();
this._itemCreatedHandler = Function.createDelegate(this, this._itemCreatedCallback);
this._myComponent.add_itemCreated(this._itemCreatedHandler);
}
_itemCreatedCallback : function(sender, e) {
this.works();
}
The this reference works correctly. I can now reference the instance of the class.