2
我試圖創建一個應用程序與li
元素作爲可選擇的意見。該應用程序要求使用單擊和拖動界面選擇多個元素。因此,我使用Backbone.js來跟蹤元素狀態和視圖,以及jQuery UI可選擇用於選擇UI。集成Backbone.js與jQuery UI可選
目前,我擁有的唯一結構是主應用視圖,li
元素的模型和視圖以及模型的集合。
什麼是最好的方式來構建這個,使我的主App視圖可以跟蹤和選擇元素進行交互?
我試圖創建一個應用程序與li
元素作爲可選擇的意見。該應用程序要求使用單擊和拖動界面選擇多個元素。因此,我使用Backbone.js來跟蹤元素狀態和視圖,以及jQuery UI可選擇用於選擇UI。集成Backbone.js與jQuery UI可選
目前,我擁有的唯一結構是主應用視圖,li
元素的模型和視圖以及模型的集合。
什麼是最好的方式來構建這個,使我的主App視圖可以跟蹤和選擇元素進行交互?
這是我剛纔做的一個刪節版本。它可能過於複雜,你需要什麼,但它確實有效。我需要能夠以編程方式選擇/取消選擇項目以及讓jQuery可選擇處理它,這就是爲什麼該模型具有Selected
屬性。採用這種方法,您可以執行model.set({Selected:true})
,並且所有內容在UI中保持同步。
新增的jsfiddle進行論證:http://jsfiddle.net/phoenecke/VKRyS/5/
然後在你的應用程序視圖,你可以這樣做:
_.each(collection.where({Selected:true}), function(item){
// do something with item
});
希望它能幫助。
ItemView控件:
var ItemView = Backbone.View.extend({
tagName: "li",
initialize: function(options) {
this.listenTo(this.model, 'change:Selected', this.selectedChanged);
},
render: function() {
this.$el.html(template(this.model));
// add cid as view's id, so it can be found when jQuery-selectable says selection changed (in ListView below).
this.$el.attr({
'id': this.model.cid
});
this.selectedChanged();
return this;
},
selectedChanged: function() {
// respond to model's Selected change event.
// This way, you can programmatically change it, ie. model.set({Selected:true}).
// but usually this class is already on the view,
// since jQuery selectable adds/removes it. it does not hurt to re-add it,
// but you could check for the class.
if(this.model.get('Selected')) {
this.$el.addClass('ui-selected');
} else {
this.$el.removeClass('ui-selected');
}
}
});
的ListView:
var ListView = Backbone.View.extend({
initialize: function(options) {
this.listenTo(this.collection, 'reset', this.render);
this._views = {};
},
render: function() {
this.collection.each(function(item) {
var view = new ItemView({model: item});
this._views[item.cid] = view;
this.$el.append(view.render().el);
}, this);
this.setupSelectable();
},
setupSelectable: function() {
var thisView = this;
// Set up JQuery UI Selectable
this.$el.selectable({
filter: 'li',
selected: function(event, ui) {
var cid = ui.selected.id;
var view = thisView._views[cid];
if(view) {
// I think I only did this stuff to keep the model's Selected
// attribute in sync with the UI.
// this will trigger a redundant call to 'selectedChanged' in the
// ItemView, but it has no negative effect.
view.model.set({
Selected: true
});
}
},
unselected: function(event, ui) {
var cid = ui.unselected.id;
var view = thisView._views[cid];
if(view) {
view.model.set({
Selected: false
});
}
}
});
}
});
看起來這將做的工作。骨幹網新手,所以這樣的例子總是有幫助,謝謝。 – NickCSE 2013-03-06 18:52:19
是不是很奇怪,ItemViews本身不聽選擇的改變,但它已經在父視圖中被聆聽了嗎? – 2014-08-07 09:14:19