UPDATE: Resolved by updating the Lightning Component Bundles being created to API version 43.0
ALSO: For future reference, the 8th line of the second code block (var el = els[i];
) should instead be let el = els[i];
to work properly.
I have code that creates a number of components within a loop. Sometimes when creating these components, I want to dynamically add an event handler.
Here is a working example of this:
createOneComponent : function(component, attributes, name) {
$A.createComponent(
name,
attributes,
function(el, status, err) {
if (status === "SUCCESS") {
var body = component.get("v.body");
// ADDING HANDLER HERE
if (true) {
el.addEventHandler("c:AF_LinkEvent", function(event) {
// DO THINGS HERE
});
}
body.push(el);
component.set("v.body", body);
} else if (status === "ERROR") {
console.log("Error: " + err);
}
}
);
}
However, during the course of development I discovered that for components of different complexity, these callbacks weren't always coming back in order, meaning components were being placed on the page out of order. To solve this, I instead implemented createComponents
, like so:
createManyComponents : function(component, compList) {
$A.createComponents(
compList,
function(els, status, err) {
if (status === "SUCCESS") {
var body = component.get('v.body');
for (var i=0; i<els.length; i++) {
var el = els[i];
// ADDING HANDLER HERE
if (true) {
el.addEventHandler('c:AF_LinkEvent', function(event) {
// DO THINGS HERE
});
}
body.push(el);
}
component.set('v.body', body);
} else if (status === "ERROR") {
console.log("Error: " + err);
}
}
);
}
When I use this method in this context, I get the following error:
This page has an error. You might just need to refresh it. Error in $A.getCallback() [el.addEventHandler is not a function] Callback failed: aura://ComponentController/ACTION$getComponent Failing descriptor: {c:AF_PageWrapper}
It's also worth noting that when I log el
in either example, I get objects with different attributes. So it seems like createComponent
and createComponents
return a different type of object, with createComponent
returning a proper DOM object while createComponents
returns something else.
Is this working as intended? Have I missed something? Can anyone suggest a workaround for this problem? Thanks in advance.
{!v.body}
component and get attributes to tell you which component was firedevent.getSource().get("v.name")
orevent.getSource().get("v.id")