Reputation: 436
I've encountered a little bit of strange behavior with JavaScript whilst trying to get access to an object variable that does exist but not at run-time.
The following shows the initiation of the object which I'm trying to access:
app.examView = new app.ExamView({el: $("#main_wrap"), model: model});
Here is the definition and the call to the object creation where I'm trying to get access to the app.examView variable.
app.ExamView = Backbone.View.extend({
initialize: function(){
this.render();
this.calculatorView = new app.ExamCalculatorView({el: $("#exam_calculator_container"), model: this.model});
this.questionView = new app.ExamQuestionView({el: $("#exam_question"), model: this.model});
Logging the examView variable here returns undefined:
var app = app || {};
app.ExamQuestionView = Backbone.View.extend({
initialize: function(){
console.log(app.examView);
Although, the object is accessible via the console:
Any help would be greatly appreciated.
Upvotes: 0
Views: 93
Reputation: 436
Turns out that the code that was responsible was:
app.ExamAnswerView = Backbone.View.extend({
initialize: function() {
...
},
app.examView will not be accessible until initialize has finished executing.
Using a timeout to wait until the function has finished executing, solved the problem.
setTimeout(function() {
app.examView.calculatorView.refresh();
}, 100);
Using a delay isn't preferred, but it's now giving access to the variable.
Seems using promises would be handy here!
Upvotes: 0
Reputation: 8403
I'd assume that your Backbone View is getting it's render()
called before DOM is ready. Is your code wrapped in $(document).ready()
?
The "strange behavior" is because the element becomes available after the DOM has been finalized.
Upvotes: 1