Reputation: 9131
This jsFiddle highlights my issue.
It is mimicking some functionality I have where an Object is defined and sent to the Page via socket.io.
I have a setInterval function checking if Pots
is a function, and when it is I fire an Event. During that Event I try to instantiate a new instance of Pots
only to be told that it is undefined.
The code:
var Pots;
$(document).ready(function(){
var timerId = 0;
var otherTimer = 0;
otherTimer = setInterval(function() { console.log("Creating"); Pots = function() {}; }, 5000);
timerId = setInterval(function() {
console.log("Checking");
if (_.isFunction(Pots)) {
console.log(Pots);
clearInterval(timerId);
clearInterval(otherTimer);
var evt = document.createEvent('Event');
evt.initEvent('ObjectsAvailable', true, true);
document.dispatchEvent(evt);
}
}, 1000);
});
document.addEventListener('ObjectsAvailable', function(e) {
console.log(Pots);
var Pots = new Pots();
});
EDIT
Posted this comment below:
I should point out that Pots
is actually a Backbonejs Collection with this declaration: var Pots = Backbone.Collection.extend({model: Pot});
. The reason I did the event is because there IS a time when "Pots" isn't set (probably before the browser has loaded the file with Pots declared). The jsFiddle was just to simulate that time exists. In my actual code "otherTimer" doesn't exist and Pots IS eventually a Function but when I try to use it during the ObjectsAvailable
event, it doesn't work.
Upvotes: 0
Views: 105
Reputation: 413720
You never set the global variable "Pots" to any value, so it remains undefined.
The "ObjectsAvailable" handler looks like it attempts to set it, but
Another note: the fiddle is set up with the code to be run in the window "load" handler, so the "ready" handler is redundant.
Upvotes: 3