[英]Rendering with Backbone
I am trying to learn backbone and I was following along the code school backbone.js course to build my own backbone app. 我正在尝试学习骨干,并且一直遵循代码学校的ribs.js课程来构建自己的骨干应用程序。 So far I have this code but I am having problems with rendering anything. 到目前为止,我已经有了这段代码,但是在渲染任何东西时都遇到了问题。
var PostsApp = new (Backbone.View.extend({
Collections: {},
Models: {},
Views: {},
start: function(bootstrap){
var posts = new PostsApp.Collections.Posts(bootstrap.posts);
var postsView = new PostsApp.Views.Posts({collection: posts});
this.$el.append(postsView.render().el);
}
}))({el : document.body});
PostsApp.Models.Post = Backbone.Model.extend({});
PostsApp.Collections.Posts = Backbone.Collection.extend({});
PostsApp.Views.Post = Backbone.View.extend({
template: _.template("<%= name %>"),
render: function(){
this.$el.html(this.template(this.model.toJSON()));
}
});
PostsApp.Views.Posts = Backbone.View.extend({
render: function(){
this.collection.forEach(this.addOne, this);
},
addOne: function(post){
var postView = new PostsApp.Views.Post({model:post});
this.$el.append(postView.render().el);
}
});
var bootstrap = {
posts: [
{name:"gorkem"},
{name: "janish"}
]
}
$(function(){
PostsApp.start(bootstrap);
});
I am just trying to create a very simple backbone app, CodeSchool is great but it not good at combining the pieces together and when I try to do that myself I am having problems. 我只是想创建一个非常简单的主干应用程序,CodeSchool很棒,但是不能很好地将各个部分组合在一起,当我自己尝试这样做时,我遇到了问题。
So far the error I am getting is "Uncaught TypeError: Cannot read property 'el' of undefined" in the addOne function of the Posts View. 到目前为止,我得到的错误是Posts View的addOne函数中的“ Uncaught TypeError:无法读取未定义的属性'el'”。 Any help would be much appreciated. 任何帮助将非常感激。
edit: The answer below solved my initial problem, but I also set up an express server to send data to the front end with the code : 编辑:下面的答案解决了我最初的问题,但是我还设置了一个快递服务器,使用代码将数据发送到前端:
app.get('/tweet', function(req,res){
res.send([{ name: 'random_name' }, {name: 'diren_gezi'}] );
});
and then I am trying to fetch this data to my collection like this : 然后我试图像这样将这些数据提取到我的集合中:
var PostsApp = new (Backbone.View.extend({
Collections: {},
Models: {},
Views: {},
start: function(bootstrap){
var posts = new PostsApp.Collections.Posts(bootstrap.posts);
posts.url = '/tweet';
posts.fetch();
var postsView = new PostsApp.Views.Posts({collection: posts});
postsView.render();
this.$el.append(postsView.el);
}
}))({el : document.body});
But in the page the initial data (name: gorkem and name: janish) is displayed instead of the recently fetched data.. 但是在页面中,将显示初始数据(名称:gorkem和名称:janish),而不是最近获取的数据。
This is the problem line (I see it in a few spots). 这是问题所在(我在几个地方都可以看到)。
this.$el.append(postsView.render().el);
Try changing it to 尝试将其更改为
postsView.render();
this.$el.append(postsView.el);
Render function doesn't return a function to self (the object with a reference to el). 渲染函数不会将函数返回给self(引用el的对象)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.