2012-09-06 35 views
0

IM,試圖做什麼IM是是顯示一個笑話每個用戶點擊一個事件.get_joke時間:我的繼承人骨幹的應用程序代碼:骨幹模型屬性沒有定義?利用骨幹,構建我的客戶端應用程序

JokeModel = Backbone.Model.extend({ 
    url: '/jokes' 
    initialize: function() { 
     this.fetch(); 
    } 
}); 

JokeView = Backbone.View.extend({ 
    template: _.template("<p><%= joke %></p>") 
    events: { 
     "click .get_joke" : "render" 
    } 
    render: function() { 
     var newJoke = new JokeModel; 
     $(this.el).html(this.template(newJoke.toJSON())); 
    } 
}); 

newJokeView = new JokeView; 

問題時,我點擊.get_joke它deosnt呈現笑話來看,我知道該模型已被提取,因爲我用的console.log檢查,但它說笑話尚未確定,但我dont't知道問題出在哪裏。感謝

回答

3

首先,你不能相信什麼console.log最高審計機關對複雜對象:

正在發生的事情是,joke.fetch()是異步的,當你調用jokeView.render()該模型還沒有準備好。

你應該修改一點點你的架構和分配適當的查看到每一個笑話,所以你可以爲每個笑話一種觀點認爲,正在顯示在需要時照顧。

// code simplified an not tested 
JokeModel = Backbone.Model.extend({ 
    url: '/jokes' 
}); 

// This View is new and it is taking care only for the common event "click .get_joke" 
// which is not related with any Joke in particular 
// This View should be in charge of the JokesCollection 
// but I don't want to make things more complicate 
JokeControls = Backbone.View.extend({ 
    events: { 
    "click .get_joke" : "render" 
    }, 

    getJoke: function(){ 
    var joke = new JokeModel(); 
    var view = new JokeView({ model: joke, el: this.$el.find(".joke-wrapper") }); 
    joke.fetch(); 
    }, 
}); 


// This is the View that is related with unique Joke 
JokeView = Backbone.View.extend({ 
    template: _.template("<p><%= joke %></p>"), 

    initialize: function(){ 
     // see how it shows itself when the Model is ready 
     this.model.on("change", this.render, this); 
    }, 

    render: function() { 
     this.$el.html(this.template(this.model.toJSON())); 
    } 
}); 

// Activate the Joke Controls 
newJokeControls = new JokeControls({ el: "#joke-controls" }); 
0

嘗試以下操作:

JokeModel = Backbone.Model.extend({ 
    url: '/jokes' 
    parse : function(data) { 
     console.log(data); 
     return data; 
    } 
    initialize: function() { 
     this.fetch(); 
    } 
}); 

我還登出如下:

newJoke.toJSON() 

要見你實際上試圖渲染。