我想出了一个办法!!!
- 为 SurveyBuilder 视图在父视图下创建一组子视图(在我的示例中,this.qbViews 维护一组 QuestionBuilder 视图)
- 对于您的收藏(在我的情况下为 this.questions),使用to设置
remove
事件。这意味着每次从 this.questions 中删除某些内容时它都会运行on
updateIndexes
updateIndexes
- 在
events
父视图的对象中,sortstop
为您的可排序对象添加一个事件(在我的情况下startstop .question-builders
,它是持有 questionBuilder 视图的 UL)也指向updateIndexes
在updateIndexes
执行以下操作:
updateIndexes: function(){
//Go through each of our Views and set the underlying model's question_number to
//whatever the index is in the list + 1
_.each(this.qbViews, function(qbView){
var index = qbView.$el.index();
//Only actually `set`s if it changed
qbView.model.set('question_number', index + 1);
});
},
还有我的 SurveyBuilder 视图的完整代码:
v.SurveyBuilder = v.Page.extend({
template: JST["app/templates/pages/survey-builder.hb"],
initialize: function() {
this.qbViews = []; //will hold all of our QuestionBuilder views
this.questions = new c.Questions(); //will hold the Questions collection
this.questions.on('add', this.addQuestion, this);
this.questions.on('remove', this.updateIndexes, this); //We need to update Question Numbers
},
bindSortable: function() {
$('.question-builders').sortable({
items: '>li',
handle: '.move-question',
placeholder: 'placeholder span11'
});
},
addQuestion: function(question) {
var view = new v.QuestionBuilder({
model: question
});
//Push it onto the Views array
this.qbViews.push(view);
$('.question-builders').append(view.render().el);
this.bindSortable();
},
updateIndexes: function(){
//Go through each of our Views and set the underlying model's question_number to
//whatever the index is in the list + 1
_.each(this.qbViews, function(qbView){
var index = qbView.$el.index();
//Only actually `set`s if it changed
qbView.model.set('question_number', index + 1);
});
},
events: {
'click .add-question': function() {
this.questions.add({});
},
//need to update question numbers when we resort
'sortstop .question-builders': 'updateIndexes'
}
});
这是完整代码的我的视图文件的永久链接:
https ://github.com/nycitt/node-survey-builder/blob/1bee2f0b8a04006aac10d7ecdf6cb19b29de8c12/app/js/survey-builder/views.js