Reputation: 4008
I'm adding listeners to one link or multiple links, using the following code:
function getData() {
var context = {};
context['triggers'] = triggers();
context['msg'] = msg;
return context
}
function triggers() {
var arr = [];
document.querySelectorAll('.trigger').forEach(function (trigger, index) {
arr[index] = {};
arr[index]['trigger'] = trigger;
});
return arr;
}
function addListeners(data) {
data.triggers.forEach(function (trigger) {
trigger.addEventListener('click', change)
});
}
data = geData()
Trigger is an anchor:
I get the following error:
TypeError: trigger.addEventListener is not a function
Upvotes: 0
Views: 750
Reputation: 1074365
The object in triggers
isn't the anchor, it's an object that contains the anchor as a property called trigger
. So:
function addListeners(data) {
data.triggers.forEach(function (entry) { // *** `entry` instead of `trigger`
entry.trigger.addEventListener('click', change)
// -----^^^^^^
});
}
We know this because of this code:
function triggers() {
var arr = [];
document.querySelectorAll('.trigger').forEach(function (trigger, index) {
arr[index] = {};
arr[index]['trigger'] = trigger;
});
return arr;
}
That's clearly creating an object, then setting the element as a trigger
property on it.
Side note: You can use property initializers and property literal syntax in several places where you're using strings, and FWIW you can apply map
to a NodeList
:
function getData() {
return {
triggers: triggers(),
msg: msg
};
}
function triggers() {
return Array.prototype.map.call(
document.querySelectorAll('.trigger'),
function(anchor) {
return {trigger: anchor};
}
);
}
function addListeners(data) {
data.triggers.forEach(function (entry) {
entry.trigger.addEventListener('click', change)
});
}
data = geData();
Upvotes: 1