For some reason, I cannot get the length of an array (it is undefined if it's unpopulated, right?).
define(function() {
'use strict';
var self = {},
events = {};
self.publish = function publish(eventName, data) {
var subscribers, x, length;
if (events[eventName]) {
return false;
}
subscribers = events[eventName];
for (x = 0, length = subscribers.length || 0; x < length; x += 1) {
subscribers[x](data);
}
return true;
};
self.subscribe = function subscribe(eventName, func) {
if (!events[eventName]) {
events[eventName] = [];
}
events[eventName].push(func);
};
return self;
});
JSLint says: "Expected ';' and instead saw ','." Jasmine says "TypeError: Cannot read property 'length' of undefined"
Why isn't length set to 0? Have I misunderstood the syntax an operations here?
for (x = 0, subscribers.length || 0; x < length; x += 1) {tofor (x = 0; subscribers.length == 0 || x < subscribers.length; x += 1) {subscribersis an array? It seems to beundefined.it is undefined if it's unpopulated, rightno, it's zero. Makes sense - there are zero objects in the array, hence the length is zero.events[eventName]and drop out if it has a value. So in the next line, it means it doesn't have a value, sosubscribersis likelyundefinedat that point.subscriberswill always beundefinedwith this code. Because you returnfalsewhenevents[eventName]is truthy