我有一个包含图像的文件夹;我在文件夹上传时调用fetch,我的GET返回HTML(没有json等)中的以下响应
<h1>Index of /backbone_images/uploads</h1>
<ul><li><a href="/backbone_images/"> Parent Directory</a></li>
<li><a href="2012-12-11%2015.30.221.jpg"> 2012-12-11 15.30.221.jpg</a></li>
<li><a href="ian1.jpg"> in1.jpg</a></li>
<li><a href="imagedummy.png"> imagedummy.png</a></li>
我试图用以下代码将我提取的数据渲染到模型中:
window.Person = Backbone.Model.extend({});
window.AddressBook = Backbone.Collection.extend({
url: 'uploads/',// declare url in collection
model: Person
});
window.Addresses = new AddressBook();
window.AppView = Backbone.View.extend({
el: $('#left_col'),
initialize: function() {
Addresses.bind('reset', this.render); // bind rendering to Addresses.fetch()
},
render: function(){
console.log(Addresses.toJSON());
}
});
window.appview = new AppView();
Addresses.fetch();
但是没有任何内容被渲染或附加到我的左列:那么-->我可以从包含这样图像的目录中提取吗?此外,我可以对HTML响应做些什么?我如何将其加载到模型中,使其呈现等(如果有任何方法的话)?
您应该将HTML响应更改为JSON格式,以便Backbone
能够正确地呈现它(尽管有一种方法可以显示上面的HTML
,但这不是推荐的方法,因为最好呈现原始数据)。
你可以这样做:
HTML:
<div id="container">
</div>
<script id="template" type="text/html">
<li><img src=<%- dir %><%- image %> /></li>
</script>
JavaScript:
$(function(){
/** Your response object would look something like this. */
var json = {'parent_directory':
{'dir_desc': 'Index of /backbone_images/uploads',
'images': [
{'dir': '/images/', 'image': 'image1.jpg'},
{'dir': '/images/', 'image': 'image2.jpg'},
{'dir': '/images/', 'image': 'image3.jpg'}
]
}};
/** Create a simple Backbone app. */
var Model = Backbone.Model.extend({});
var Collection = Backbone.Collection.extend({
model: Model
});
var View = Backbone.View.extend({
tagName: 'ul',
initialize: function() {
this.render();
},
template: _.template($('#template').html()),
render: function() {
_.each(this.collection.toJSON(), function(val){
this.$el.append(this.template({
image: val.image,
dir: val.dir}));
}, this);
return this;
}
});
/** Create a new collection and view instance. */
var newColl = new Collection(json.parent_directory.images);
var newView = new View({collection: newColl});
$('#container').html(newView.el);
});
您应该将其绑定到sync
事件
此外,我更喜欢使用listenTo
this.listenTo(Addresses, 'sync', this.render)