同一类中不能访问变量(Can't access variable inside same c

2019-10-20 11:33发布

var BooksView = Backbone.View.extend({

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

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

和我的路由器:

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"
      });
   }
});

如何访问的变量? this.myVar似乎并不奏效,尽管变量被设置在同一类中?

Answer 1:

作为骨干版本1.1.0 Backbone.js的不再自动将所有的选项给你,但你仍然可以手动将里面自己做初始化功能。

例如

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


Answer 2:

你可以像视图模型设置数据: -

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

然后在视图定义模型,并写

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


文章来源: Can't access variable inside same class