我正在做一个项目来测试这个骨干样板(https://github.com/tbranyen/backbone-boilerplate),但我在渲染视图时遇到了问题。我第一次调用 beforeRender,集合(图片)是空的,因为 Flickr 照片的获取仍在进行中。但是当加载数据时,我可以在我的 Pics.Collection 的“解析”函数中看到它们(带有断点),我的视图的 beforeRender 再也不会被调用。
我的 router.js :
define([
// Application.
"app",
"modules/pics"
],
function(app, HomePage, Pics) {
// Defining the application router, you can attach sub routers here.
var Router = Backbone.Router.extend({
initialize: function() {
// Init collections
var collections = {
pics: new Pics.Collection()
};
console.log('collec');
// Register in the router
_.extend(this, collections);
},
routes: {
"": "pics"
},
pics: function() {
this.reset();
app.useLayout().setViews({
"#content": new Pics.Views.List({ pics: this.pics }),
"header": new Backbone.View({
tagName: "span",
beforeRender: function() {
this.$el.html("Header Pics");
}
})
}).render();
this.pics.fetch();
},
reset: function() {
if (this.pics.length) {
this.pics.reset();
}
}
});
return Router;
});
我的模块 pics.js :
define([
"app"
], function(app) {
var Pics = app.module();
Pics.Model = Backbone.Model.extend({ });
Pics.Collection = Backbone.Collection.extend({
model: Pics.Model,
url: function() {
return "http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=?";
},
cache: true,
parse: function(obj) {
return obj.items;
}
});
Pics.Views.Item = Backbone.View.extend({
template: "pics/item",
tagName: "li",
serialize: function() {
return { model: this.model };
},
initialize: function() {
this.listenTo(this.model, "change", this.render);
}
});
Pics.Views.List = Backbone.View.extend({
template: "pics/list",
serialize: function() {
return { collection: this.options.pics };
},
beforeRender: function() {
this.options.pics.each(function(pic) {
this.insertView("#pics-list", new Pics.Views.Item({
model: pic
}));
}, this);
},
initialize: function() {
this.listenTo(this.options.pics, {
"reset": this.render(),
"request": function() {
this.$("ul").parent().html("<img src='/app/img/spinner-gray.gif'>");
}
});
}
});
return Pics;
});
list.html(模板):
<h1>Liste des photos</h1>
<div>
<div class="loading"></div>
<ul id="pics-list"></ul>
</div>
item.html(模板):
<li>
<img src="<%= model.get("link") %>" />
</li>
索引.html:
<main role="main" id="main">
<nav>
<ul>
<li><a href="">Home</a></li>
</ul>
</nav>
<header></header>
<aside></aside>
<section id="content"></section>
<footer>
Copyright 2013
</footer>
</main>
两天以来,我在论坛上和我自己搜索是否存在现有问题,但我找不到问题所在。
在此先感谢,皮埃里克。