首先,您不能相信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" });