14

我是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" }
    ]
}
4

3 回答 3

14

您需要做的最重要的事情是将工作流与视图本身分开。也就是说,您应该有一个对象来协调视图之间的工作流,保存输入到视图中的数据,并使用视图的结果(通过事件或其他方式)来确定去向下一个。

我已经在博客中对此进行了更详细的介绍,这里有一个非常简单的向导式界面示例:

http://lostechies.com/derickbailey/2012/05/10/modeling-explicit-workflow-with-code-in-javascript-and-backbone-apps/

和这里:

http://lostechies.com/derickbailey/2012/05/15/workflow-in-backbone-apps-triggering-view-events-from-dom-events/

这是第一篇文章中的基本代码,它显示了工作流对象以及它如何协调视图:


orgChart = {

  addNewEmployee: function(){
    var that = this;

    var employeeDetail = this.getEmployeeDetail();
    employeeDetail.on("complete", function(employee){

      var managerSelector = that.selectManager(employee);
      managerSelector.on("save", function(employee){
        employee.save();
      });

    });
  },

  getEmployeeDetail: function(){
    var form = new EmployeeDetailForm();
    form.render();
    $("#wizard").html(form.el);
    return form;
  },

  selectManager: function(employee){
    var form = new SelectManagerForm({
      model: employee
    });
    form.render();
    $("#wizard").html(form.el);
    return form;
  }
}

// implementation details for EmployeeDetailForm go here

// implementation details for SelectManagerForm go here

// implementation details for Employee model go here
于 2012-05-31T17:07:14.380 回答
5

我将 Derick 的答案标记为已接受,因为它比我所拥有的更干净,但这不是我可以在我的情况下使用的解决方案,因为我有 50 多个屏幕要处理,我无法闯入漂亮的模型 - 我已经得到了他们的内容,只需复制它们。

这是我想出的处理屏幕切换逻辑的 hacky 模型代码。我敢肯定,随着我继续努力,我最终会更多地重构它。

var Wizard = Backbone.Model.extend({

    initialize: function(options) {
        this.set({
            pathTaken: [0],
            // instantiate the screen definitions as screenResponses
            screenResponses: _(this.screens).map(function(s){ return new s; })
        });
    },

    currentScreenID: function() {
        return _(this.get('pathTaken')).last();
    },

    currentScreen: function() {
        return this.screens[this.currentScreenID()];
    },

    isFirstScreen: function(screen) {
        screen = screen || this.currentScreen();
        return (_(this.screens).first() === screen);
    },

    // This function should be overridden by wizards that have
    // multiple possible "finish" screens (depending on path taken)
    isLastScreen: function(screen) {
        screen = screen || this.currentScreen();
        return (_(this.screens).last() === screen);
    },

    // This function should be overridden by non-trivial wizards
    // for complex path handling logic
    nextScreenID: function(currentScreenID, currentScreen) {
        // default behavior is to return the next screen ID in the list
        return currentScreenID + 1;
    },

    nextScreen: function() {
        // return immediately if on final screen
        if (this.isLastScreen()) return;
        // otherwise get next screen id from nextScreenID function
        nsid = this.nextScreenID(this.currentScreenID(), this.currentScreen());
        if (nsid) {
            this.get('pathTaken').push(nsid);
            return nsid;
        }
    },

    prevScreen: function() {
        // return immediately if on first screen
        if (this.isFirstScreen()) return;
        // otherwise return the previous screen in the list
        prevScreenID = _(_(this.get('pathTaken')).pop()).last();
        return this.screens[prevScreenID];
    }

});

var ChocolateWizard = Wizard.extend({

    initialize: function(options) {
        Wizard.prototype.initialize.call(this); // super()

        this.set({
            wizardType: 'Chocolate',
        });
    },

    nextScreenID: function(csid, cs) {
        var resp = this.screenResponses(csid);
        this.nextScreenController.setState(csid.toString()); // have to manually change states
        if (resp.nextScreenID)
            // if screen defines a custom nextScreenID method, use it
            return resp.nextScreenID(resp, this.get('screenResponses'));
        else
            // otherwise return next screen number by default
            return csid + 1;
    },

    // convenience function
    screenResponses: function(i) {
        return this.get('screenResponses')[i];
    },

    screens: [
        // 0
        Backbone.Model.extend({
            title : "Chocolate quiz",
            schema: {
                name: 'Text',
                likesChocolate:  {
                    title: 'Do you like chocolate?',
                    type: 'Radio',
                    options: ['Yes', 'No']
                }
            },
            nextScreenID: function(thisResp, allResp) {
                if (thisResp.get('likesChocolate') === 'Yes')
                    return 1;
                else
                    return 2;
            }
        }),
        // 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' ]
                }
            },
            nextScreenID: function(thisResp, allResp) {
                return 3; // skip screen 2
            }
        }),
        // 2
        Backbone.Model.extend({
            title : "So you don't like chocolate.",
            schema: {
                otherSweet:  {
                    title: 'What type of sweet do you prefer then?',
                    type: 'Text'
                }
            }
        }),
        // 3
        Backbone.Model.extend({
            title : "Finished - thanks for taking the quiz!"
        }
    ]
});
于 2012-06-01T16:07:21.977 回答
0

CloudMunch,我们有类似的需求并构建了Marionette-Wizard

wrt 显式 Q,在此向导中,所有内容都存储在 localStorage 中,并且可以作为类似于您指定格式的对象进行访问。

于 2016-12-21T07:34:53.513 回答