我是backbone.js 的新手,在解决我设计“向导”类型流程(又名多步骤表单)时遇到的问题时遇到了一些麻烦。该向导应该能够根据用户对问题的响应处理不同的屏幕分支逻辑,随着用户的进行存储对每个屏幕的响应,最后能够将所有表单响应(每一步)序列化为一个大对象(可能是 JSON)。向导问题每年都会发生变化,我需要能够同时支持多个类似的向导。
就创建屏幕(使用主干形式)而言,我已经掌握了基础知识,但我现在已经到了要保存用户输入的地步,我想不出最好的方法来做到这一点。我见过的大多数示例都有一种特定类型的对象(例如Todo
),您只需创建它们的集合(例如TodoList
),但是由于屏幕类型不同,我有一个混杂的 Backbone.Model 定义,所以它没有看起来并不那么简单。关于我应该如何实例化我的向导及其包含的屏幕并记录用户响应的任何指示?
如果它有帮助,我可以用我的视图代码发布一个 jsfiddle,到目前为止只能向前和向后屏幕(没有用户输入响应记录或屏幕分支)。
var Wizard = Backbone.Model.extend({
initialize: function(options) {
this.set({
pathTaken: [0]
});
},
currentScreenID: function() {
return _(this.get('pathTaken')).last();
},
currentScreen: function() {
return this.screens[this.currentScreenID()];
},
isFirstScreen: function(screen) {
return (_(this.screens).first() == this.currentScreen());
},
// This function should be overridden by wizards that have
// multiple possible "finish" screens (depending on path taken)
isLastScreen: function(screen) {
return (_(this.screens).last() == this.currentScreen());
},
// This function should be overridden by non-trivial wizards
// for complex path handling logic
nextScreen: function() {
// return immediately if on final screen
if (this.isLastScreen(this.currentScreen())) return;
// otherwise return the next screen in the list
this.get('pathTaken').push(this.currentScreenID() + 1);
return this.currentScreen();
},
prevScreen: function() {
// return immediately if on first screen
if (this.isFirstScreen(this.currentScreen())) return;
// otherwise return the previous screen in the list
prevScreenID = _(_(this.get('pathTaken')).pop()).last();
return this.screens[prevScreenID];
}
});
var ChocolateWizard = Wizard.extend({
nextScreen: function() {
//TODO: Implement this (calls super for now)
// Should go from screen 0 to 1 OR 2, depending on user response
return Wizard.prototype.nextScreen.call(this);
},
screens: [
// 0
Backbone.Model.extend({
title : "Chocolate quiz",
schema: {
name: 'Text',
likesChocolate: {
title: 'Do you like chocolate?',
type: 'Radio',
options: ['Yes', 'No']
}
}
}),
// 1
Backbone.Model.extend({
title : "I'm glad you like chocolate!",
schema: {
chocolateTypePreference: {
title: 'Which type do you prefer?',
type: 'Radio',
options: [ 'Milk chocolate', 'Dark chocolate' ]
}
}
}),
//2
Backbone.Model.extend({
title : "So you don't like chocolate.",
schema: {
otherSweet: {
title: 'What type of sweet do you prefer then?',
type: 'Text'
}
}
})
]
});
wizard = new ChocolateWizard();
// I'd like to do something like wizard.screens.fetch here to get
// any saved responses, but wizard.screens is an array of model
// *definitions*, and I need to be working with *instances* in
// order to fetch
编辑:根据要求,我希望看到已保存的向导的 JSON 返回值看起来像这样(作为最终目标):
wizardResponse = {
userID: 1,
wizardType: "Chocolate",
screenResponses: [
{ likesChocolate: "No"},
{},
{ otherSweet: "Vanilla ice cream" }
]
}