通过建立my simple blog app我正在进行的自我思考过程中,我找到问题的解决方案并遇到新问题。
现在成功从第一个视图路由到第二个视图,并且页面由新视图html填充。
从第二个视图成功保存到db新帖子,这是一个添加新帖子的表单。
但是在第一个视图中,我无法查看已保存的帖子,实际上列出了它们的标题。
Js控制台错误消息是
[Error] TypeError: undefined is not a function (evaluating 'this.template2(each)')
(anonymous function) (app.js, line 34)
forEach ([native code], line 0)
forEach (underscore-min.js, line 5)
(anonymous function) (backbone-min.js, line 1)
renderPostsListItem (app.js, line 33)
f (backbone-min.js, line 1)
trigger (backbone-min.js, line 1)
_onModelEvent (backbone-min.js, line 1)
f (backbone-min.js, line 1)
trigger (backbone-min.js, line 1)
set (backbone-min.js, line 1)
success (backbone-min.js, line 1)
j (jquery.min.js, line 2)
fireWith (jquery.min.js, line 2)
x (jquery.min.js, line 4)
(anonymous function) (jquery.min.js, line 4)
但是我在视图定义中编译了这个模板。通过在render函数中使用alert(this.colection.length)并产生2,这是正确的从我知道的db中获取的集合。
那么我的template2函数可能会出现什么问题?
此视图中使用的html模板是:
<!--Post Templates-->
<script type="text/template" id="postsListTemplate">
<h1>Blog</h1>
<h2>All Posts</h2>
<ul>aaa</ul>
<p><a href="/posts/postform">Add New Post</a></p>
</script>
<script type="text/template" id="postsListItemTemplate">
<li>{{title}}</li>
</script>
呈现这些模板的视图是:
var postsListView = Backbone.View.extend({
collection: new postsCollection(),
template1: _.template( $('#postsListTemplate').html() ),//!!!Once forgot .html().
template2: _.template( $('#postsListItemTemplate').html() ),
initialize: function(){
this.collection.fetch();
this.collection.on('add', this.renderPostsListItem, this);
},
render: function(){
this.$el.html( this.template1() );
return this;
},
renderPostsListItem: function(){
console.log("view method renderPostsListItem have been reached.");
this.ul = 'ul';
alert(this.collection.length);
this.collection.forEach(function(each){
$(this.ul).append( this.template2(each) );//!this.el or this.$el. (each) or (each.toJSON()). SOLVED: use this.$el alongside el: a string, without $().
});
return this;
},
events: {//!!events attr is not a function but an object.
"click a": 'toPostFormRoute'
},
toPostFormRoute: function(e){
console.log("view method toPostFormRoute have been reached.");
e.preventDefault();
//this.hrefOfPostForm = $( e.currentTarget ).attr("href");
//Backbone.navigate( this.hrefOfPostForm , {trigger: true});
Backbone.history.navigate( '/posts/postform' , {trigger: true});
console.log("view method toPostFormRoute have been reached.");
}
});
此视图中使用的模型和集合是:
var postModel = Backbone.Model.extend({});
var postsCollection = Backbone.Collection.extend({
model: postModel,
url: "/posts"
});