我使用主干来构建我的客户端应用程序,我想做的是每次用户在事件上单击 .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 时,问题是它不会将笑话渲染到 View 中,我知道模型已被获取,因为我检查了 console.log,但它说笑话尚未定义,但我没有知道问题出在哪里。谢谢
最佳答案
首先,你不能相信 console.log
对复杂对象的描述:
- Backbone.js Empty Array Attribute
- Backbone.js model.get() returning 'undefined' even though I can see the attributes in console.log
发生的情况是 joke.fetch()
是异步的,当您调用 jokeView.render()
时,模型仍未准备好。
您应该稍微修改一下您的架构,并为每个笑话分配一个适当的 View ,这样您就可以为每个笑话拥有一个在需要时负责显示它的 View 。
// 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" });
关于javascript - Backbone 中的模型属性未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12299411/