Search code examples
backbone.js

Creating a wizard process in backbone.js


I'm new to backbone.js and having some trouble wrapping my head around an issue I'm having designing a "wizard" type process (a.k.a. a multi-step form). This wizard should be able to handle different screen branching logic depending on the user's response to questions, store the responses to each screen as the user progresses, and at the end be able to serialize all the form responses (every step) into one large object (probably JSON). The wizard questions will be changing from year to year, and I need to be able to support multiple similar wizards in existence at the same time.

I've got the basics down as far as creating the screens (using backbone-forms), but I'm now to the point where I want to save user input and I can't think of the best way to do it. Most of the examples I've seen have one specific type of object (e.g. Todo) and you just create a collection of them (e.g. TodoList), but I've got a mixed bag of Backbone.Model definitions due to different screen types so it doesn't seem quite so simple. Any pointers on how I should be instantiating my wizard and its contained screens, and recording user responses?

If it helps I can post a jsfiddle with my view code that so far only goes forwards and backwards screens (no user input response recording or screen branching).

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

Edit: As requested, I would like to see a JSON return value for a wizard that has been saved to look something like this (as an end goal):

wizardResponse = {
    userID: 1,
    wizardType: "Chocolate",
    screenResponses: [
      { likesChocolate: "No"},
      {},
      { otherSweet: "Vanilla ice cream" }
    ]
}

Solution

  • The big thing you need to do is make the workflow separate from the views themselves. That is, you should have an object that coordinates the work flow between the views, holds on to the data that was entered in to the views, and uses the results of the views (through events or other means) to figure out where to go next.

    I've blogged about this in more detail, with a very simple example of a wizard-style interface, here:

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

    and here:

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

    Here's the basic code from that first post, which shows the workflow object and how it coordinates the views:

    
    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