Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a wizard process in backbone.js

Tags:

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" }
    ]
}
like image 903
Abe Voelker Avatar asked May 31 '12 16:05

Abe Voelker


2 Answers

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
like image 114
Derick Bailey Avatar answered Sep 21 '22 15:09

Derick Bailey


I'm marking Derick's answer as accepted as it's cleaner than what I have, but it's not a solution I can use in my case as I have 50+ screens to deal with that I can't break into nice models - I have been given their content and simply have to replicate them.

Here's the hacky model code that I came up with which handles screen switching logic. I'm sure I'll end up refactoring it a lot more as I continue working on it.

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!"
        }
    ]
});
like image 42
Abe Voelker Avatar answered Sep 21 '22 15:09

Abe Voelker