Stefano Maglione
Stefano Maglione

Reputation: 4150

Scope in backbone

i've called a view (menuview) passing it a var (prova)but from view called it results undefined(console.log(this.model),in menuview). Can anybody help me in finding errors?

ROUTER

      home: function() {
      new BarraScreamView();
      new MenuView();
       var self=this;


      var amicizie= new Amicizie();
      amicizie.fetch({
      success: function(object) {
     console.log(object);
     var prova=object.where({invitante: Parse.User.current().id,conferma:0});//mettere      
      invitato
     var num=prova.length;

     new MenuView({model:prova});<<<---------

     },
     error: function(amici, error) {

    }
    }); 

MENUVIEW

       var MenuView = Backbone.View.extend({

    el: $("#menu_container"),

    events: {

    },

    template: Handlebars.compile(template),

    initialize: function () {
        console.log(this.model);<<<------------


    this.render();
        console.log("menuview");

    },

Upvotes: 1

Views: 91

Answers (2)

Sushanth --
Sushanth --

Reputation: 55750

The reason is quite simple..

There 2 places where you seem to be creating a new Instance of MenuView()

 home: function () {
     new BarraScreamView();
     new MenuView();     <----- First Instance here
     var self = this;
     var amicizie = new Amicizie();
     amicizie.fetch({
         success: function (object) {
             new MenuView({       <----- Second Instance here     
                 model: prova
             }); 

The views are initialized in the order in which they are loaded. When you create a new View using

new MenuView(); It will hit the initialize method of the view

 initialize: function () {
        console.log(this.model);<<<------------
 }                   ^    ^
                     |    ------ Corresponds to the model passed in
                                 But there is nothing passed here
          corresponds to the view

So it logs undefined in the first case.

Upvotes: 3

Divey
Divey

Reputation: 1719

I'm going to take a guess here...

You are creating a new menu view with new MenuView(); in your home method before you call the amicizie.fetch method. My guess is that your undefined from console.log(this.model) is from that view. Are you sure that isn't the case?

Try commenting out that view and put a console.log('error') in your amicizie.fetch error handler to make sure that there are no errors in fetching the model.

Upvotes: 1

Related Questions