我正在尝试振作起来,想做一个简单的图片库应用程序,但遇到了问题。
我想用一组项目(名为 itemsArray)实例化我的视图,然后将该集合的第一个模型加载到视图中。此视图将提供上一个和下一个按钮,并且我已经设置了事件。
我对如何将此集合传递到 Backbone 视图并告诉它加载第一个元素感到困惑。此外,使用 prev / next 操作集合似乎无法正常工作。我之前问过这个问题(主干 - 尝试使用集合中的下一个或上一个模型重新渲染视图)但认为最好将整个片段发布在这里。我在教程中看到过与此类似的示例代码,但我认为使用集合知识加载单个模型已被证明是有问题的。我在下面提供了完整的源代码:
<div id='item-container'></div>
<script type='text/template' id='tmp'>
<%=header %>
<img src='<%=assets[0].url %>' />
<div class='next-btn'>next</div> <div class='prev-btn'>prev</div>
</script>
<script>
$(document).ready(function(){
var arc={};
// 2. items to be made into an Items collection
var itemsArray=[{'id':4, 'header':'my header','detail':'my detail', 'price':'$12.25', assets:[{'url':'/tmp-images/surf.jpg'}]},
{'id':7, 'header':'my header 2','detail':'my detail 2', 'price':'$14.25', assets:[{'url':'/tmp-images/jamaica.jpg'}]},
{'id':11, 'header':'my header 3','detail':'my detail 3', 'price':'$21.00',assets:[{'url':'/tmp-images/jamaica-2.jpg'}]}
];
// 3. item class
arc.Item = Backbone.Model.extend({});
// 4. items collection made up of item
arc.Items = Backbone.Collection.extend({
model:arc.Item
});
var items = new arc.Items(itemsArray);
//console.log(menu_items);
arc.ItemsGalleryView = Backbone.View.extend({
el: $('#item-container'),
events: {'click .next-btn' : 'loadNext', 'click .prev-btn':'loadPrevious' },
template:_.template($('#tmp').text()),
initialize: function() {
_.bindAll( this, 'render' );
// 5. this is definitely wrong, trying to render template with single instance of model
// seems like I should be doing something like this.collection.at(0) or something but that isn't working
//this.render(this.model);
/* 6. works but not an array
this.render({header:'my name',assets:[
{url:'/image/some.jpg'}
]});
*/
// 7. not working header is not defined
this.render(this.collection.at(0)); // error 'header is not defined'
console.log(this.collection.at(0)); // in console this kinda looks like a model but do I need to call another method on it?
},
render: function(xModel) {
var compiled=this.template(xModel);
this.$el.html(compiled);
return this;
},
loadNext: function(){
// 8. not sure what to do here
},
loadPrevious: function(){
console.log('i want to load Previous');
// 9. not working
this.render(this.collection.prev());
}
});
var itemView=new arc.ItemsGalleryView({ collection: items });
});
</script>
任何帮助是极大的赞赏。我将如何传递一个集合?然后通过事件操纵我在集合中的位置?
谢谢