在backbone.js中创建向导过程

时间:2012-05-31 16:03:42

标签: backbone.js

我是backbone.js的新手,并且在设计一个“向导”类型的过程(a.k.a.一个多步形式)的问题上遇到了一些麻烦。该向导应该能够处理不同的屏幕分支逻辑,具体取决于用户对问题的响应,在用户进行时将响应存储到每个屏幕,最后能够将所有表单响应(每个步骤)序列化为一个大对象(可能是JSON)。向导问题每年都在变化,我需要能够同时支持多个类似的向导。

我已经掌握了创建屏幕的基础知识(使用骨干表单),但我现在已经到了想要保存用户输入的地步,我想不出最好的方法它。我见过的大多数示例都有一种特定类型的对象(例如Todo),你只需创建它们的集合(例如TodoList),但我有一个混合的Backbone。由于屏幕类型不同而导致的模型定义因此看起来并不那么简单。有关如何实例化我的向导及其包含的屏幕以及记录用户响应的任何指示?

如果有帮助我可以发布一个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" }
    ]
}

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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!"
        }
    ]
});

答案 2 :(得分:0)

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

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