Can't access variable inside same class

2019-08-03 11:56发布

问题:

var BooksView = Backbone.View.extend({

    initialize: function() {
        this.render();
    },

    render: function() {
       alert(this.myVar);
    }
});

and my router:

var BookRouter = Backbone.Router.extend({
   routes: {
      '': 'index',
      'list/:id': 'list'
   },

   index: function(){
      var booksView = new BooksView({
         el: ".content",
         myVar: "Example 1"
      });
   },
   list: function(id){
      var booksView = new BooksView({
         el: ".content",
         myVar: "Example 2"
      });
   }
});

How do I access the variable? this.myVar doesn't seem to be working, even though the variable is set inside the same class?

回答1:

As of backbone version 1.1.0 backbone.js no longer attaches all options for you automatically, however you can still do this yourself manually inside your initialize function.

For example

 initialize: function(options) {
      if (options) {
        _.extend(this, options);
      }
      this.render();
    },


回答2:

You can set the data in the model of the view like:-

 list: function(id){
  var booksView = new BooksView({
     el: ".content"     
 });
 booksView.model.set(myVar, "Example 2");
 }

And then in the view define a model and write

alert(this.model.get('myVar'));