我試圖拿起主幹,想要做一個簡單的圖片庫應用程序,但我有問題。有簡單的骨幹應用程序加載一個集合,然後動態迭代通過它的問題
我想用項目集合(名爲itemsArray)實例化我的視圖,然後將該集合的第一個模型加載到視圖中。這個視圖將提供上一個和下一個按鈕,並且我已經設置了這些事件。
我很困惑如何將這個集合傳入Backbone視圖並告訴它加載第一個元素。另外,使用prev/next操作集合似乎不能正常工作。我之前問過這個問題(backbone - trying to rerender a view with the next or previous model in a collection),但認爲如果我在這裏發佈整個片段會更好。我在教程中看到了與此類似的示例代碼,但我認爲加載具有集合知識的單一模型已證明存在問題。我已經提供了完整的源代碼如下:
<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>
任何幫助,非常感謝。我將如何通過一個集合?然後通過事件操縱我在集合中的位置?
THX
我爲上面的錯誤添加了屏幕截圖。老實說,我只是試圖讓它工作,並將其分配給this.model也沒有工作。不確定在創建時這是否與在選項對象中使用集合有關。 – timpone