0

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: Firebug console

Any help would be greatly appreciated.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, the code was wrapped in $(function () { ... });.
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.