2012-09-06 33 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() 

要见你实际上试图渲染。