Can't access variable inside same class

こ雲淡風輕ζ 提交于 2019-12-24 07:29:33

问题


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'));


来源:https://stackoverflow.com/questions/24788451/cant-access-variable-inside-same-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!