主干中的模型属性未定义
The model attribute in backbone is not defined?
我使用主干网来构建我的客户端应用程序,我想做的是每次用户点击时显示一个笑话。get_joke on a event:heres my backbone app code:
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时的问题它无法将笑话呈现到视图中,我知道模型已经被提取,因为我查看了console.log,但它说笑话还没有定义,但我不知道问题在哪里。谢谢
首先,你不能相信console.log
对复杂对象的描述:
- Backbone.js空数组属性
- Backbone.js model.get()返回';未定义';即使我可以在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" });
尝试以下操作:
JokeModel = Backbone.Model.extend({
url: '/jokes'
parse : function(data) {
console.log(data);
return data;
}
initialize: function() {
this.fetch();
}
});
我也会注销以下内容:
newJoke.toJSON()
查看实际要渲染的内容。
相关文章:
- 主干中的模型属性未定义
- JavaScript 2d 数组导致“无法读取未定义的属性'未定义'”
- JSON对象属性未定义
- Waypoint的循环,退出循环后属性未定义
- Javascript:错误“无法设置属性”..'未定义”
- 翡翠 - 显示对象属性 - 未定义
- 属性未定义,但控制台.log可以看到它
- JavaScript 对象的属性未定义
- Javascript 对象属性未定义(但属性已设置)
- DOM 元素属性未定义 - jquery / ruby on rails.
- Nodejs JSON 属性未定义
- 错误:窗口打开器的属性未定义
- angular Js:Array.lenght属性未定义
- 正在尝试访问JavaScript对象的属性=未定义
- Marionette属性未定义,请从API获取
- AngularJS作用域属性未定义
- 对象的属性未定义,尽管已指定值
- 为什么我一直收到一个错误,说对象属性未定义
- 对象属性未定义,但我看到它不是
- .map()img src属性未定义