다 단계 마법사에서 복수 자식보기 ProductView
이 포함 된 상위보기 ProductListView
이 있습니다. 사용자가 ProductView
을 클릭하면 해당 모델의 ID를 처리를 위해 서버 측으로 다시 보낼 수 있도록 어딘가에 (어레이 가능) 저장해야합니다.보기에서 배열로 항목 추가 (backbone.js)
문제 : 사용자가 클릭 한 의 id
은 어디에 저장해야합니까? 부모보기 ProductListView
에 저장하려고했으나 하위보기 ProductView
에서 부모보기의 selectedProducts
배열에 액세스 할 수 없습니다.
올바른 방법입니까? 어떻게해야합니까?
모델
ProductCollection = Backbone.Collection.extend({
model: Product,
url: '/wizard'
});
부모보기
ProductListView = Backbone.View.extend({
el: '#photo_list',
selectedProducts: {}, // STORING SELECTED PRODUCTS IN THIS ARRAY
initialize: function() {
this.collection.bind('reset', this.render, this);
},
render: function() {
this.collection.each(function(product, index){
$(this.el).append(new ProductView({ model: product }).render().el);
}, this);
return this;
}
});
아이보기
ProductView = Backbone.View.extend({
tagname: 'div',
className: 'photo_box',
events: {
'click': 'toggleSelection'
},
template: _.template($('#tpl-PhotoListItemView').html()),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
// ADDS ITS MODEL'S ID TO ARRAY
toggleSelection: function() {
this.parent.selectedProducts.push(this.model.id);
console.log(this.parent.selectedProducts);
}
});
또한 @ dbaseman의 접근 방식을 취하고 각 모델에'selected' 속성이 있습니다. 마지막으로, 선택된 제품 모델의 배열을 얻기 위해'collection.filter (function (product) {return product.selected === true;})'를 수행하면됩니다. 당신이 원한다면 당신은 쉽게 id를 뽑을() 수 있습니다. 그러나 백본이 그대로있는 한, 배열을 푸는 방식 또한 잘못되었습니다. 자녀에게 부모보기의 참조를 전달하십시오. 'var childView = new ProductView ({ 'parent': parentView}); 그리고 당신은 당신의 parentView 배열에 접근 할 수 있습니다. – jmk2142