我有包含图片的文件夹;我在文件夹uploads /上调用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();
但是我的左栏没有渲染或附加任何内容:所以 - &gt;我可以从包含这样的图像的目录中获取吗?另外我可以用HTML响应做什么,如何将其加载到模型中,使其渲染等(如果有任何方法)?
答案 0 :(得分:2)
您应该将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);
});
答案 1 :(得分:1)
您应该将其绑定到sync
事件
我也更喜欢使用listenTo
this.listenTo(Addresses, 'sync', this.render)