2013-01-10 45 views
1

這裏是我的骨幹:不要使被稱爲骨幹視圖

App.Models.Count = Backbone.Model.extend({ 
     url: this.url, 
     initialize: function() { 
      this.fetch({ 
       success: function(data, response) { 
        this.count = data.get('count'); 
        console.log(this.count); // 9, correct answer 
       } 
      }); 
     } 
    }); 

    App.Views.Count = Backbone.View.extend({ 
     tagName: 'span', 
     initialize: function(options) { 
      this.count = this.options.count; 
      console.log(options); // returns correctly 
      this.model.on('reset', this.render, this); 
     }, 
     render: function() { 
      console.log('test'); // not called 
      this.$el.html(this.model.toJSON()); 
      return this; 
     } 
    }); 

在我的路線:

var mc = new (App.Models.Count.extend({'url' : 'main-contact-count'}))(); 
var mcv = new (App.Views.Count.extend({ model: mc }))(); 
console.log(mcv); // 9, correct answer 
$('#contactCount').html(mcv); 

正如你看到的,我的render方法不會被調用。另外,似乎我的視圖在我的模型之前被調用,基於我在Firebug中看到的console.log。那是因爲異步嗎?爲什麼不叫render

回答

2

您正在以一種時髦的方式使用Backbone。下面是做到這一點的更標準的方式:

App.Models.Count = Backbone.Model.extend({ 
    urlRoot: "main-contact-count" 
}); 

App.Views.Count = Backbone.View.extend({ 
    tagName: 'span', 
    initialize: function(options) { 
     this.model.on('change', this.render, this); 
    }, 
    render: function() { 
     console.log('test'); 
     this.$el.html(this.model.toJSON()); 
     return this; 
    } 
}); 

而在路由器:

var mc = new App.Models.Count(); 
var mcv = new App.Views.Count({model: mc}); 
mc.fetch(); 
$('#contactCount').html(mcv.el); 

編輯

事實證明你正在聽的骨幹模型「復位」。這絕不會發生。嘗試聆聽「更改」而不是重置:

this.model.on('change', this.render, this); 
+0

「呈現」仍然不會觸發該更改。 – sehummel

+0

如果我讓你的改變自行調用,我得到一個錯誤'this._configure不是函數.' – sehummel

+0

你說快速修復。有沒有更好的辦法? – sehummel