我是 Backbone 的初学者,所以这是一个渲染简单模板的非常简单的示例。我在渲染这个模板时遇到了问题。它仅适用于 Chrome。当我在 MasterView 对象中的“this.collection.fetch()”为空但在 Chrome 中有我的集合之后调试此代码时。我不知道为什么它在 Chrome 中有效,但在其他浏览器中无效。
索引.html
<div class="Presentation">
</div>
<script id="slideTemplate" type="text/template">
<h1><%=slide_title %></h1>
<h2><%=slide_subheading %></h2>
<div> <%=content %> </div>
</script>
模型
define(['backbone','underscore'],function(Backbone,_){
var linkModel = Backbone.Model.extend({
defaults: {
slide_title: "slide",
slide_subheading: "sub slide 1",
content: "bla bla bla"
}
});
return linkModel;
});
收藏
define(['backbone','underscore','models/link','libs/backbone-localstorage'],function(Backbone,_,link,storage){
var linkModels = Backbone.Collection.extend({
model: link,
localStorage: new storage('links')
});
return linkModels;
});
单视图
define(['jquery','backbone','underscore'],function($,Backbone,_){
var linkView = Backbone.View.extend({
tagName: "article",
className: "slide-container",
template: $("#slideTemplate").html(),
render: function(){
var tmpl = _.template(this.template);
this.$el.html(tmpl(this.model.toJSON()));
return this;
}
});
return linkView;
});
主视图
define(['jquery',
'backbone',
'underscore',
'collections/links',
'views/linkView', 'views/data'], function($, Backbone,_,links,linksView,data){
var favsView = Backbone.View.extend({
el: $(".Presentation"),
initialize: function(){
var self = this;
this.collection = new links(slides);
_.bindAll(this, 'renderLink', 'renderAll');
this.collection.fetch();
this.renderAll();
},
renderAll: function(){
this.collection.each(
this.renderLink
);
},
renderLink: function(model){
var view = new linksView({model: model});
this.$el.append(view.render().el);
model.save();
},
render: function(){
console.log("Ready...");
}
});
return new favsView;
});