Search code examples
backbone.jsbackbone-views

rendering template html via backbone view


I have a simple page that contains a 3 step wizard. Basically, the user fills out a textbox, clicks next, which loads the next form field.

I have setup all the HTML inside a template and use that template in a backbone view.

The problem is, backbone isn't rendering the HTML inside the template. I just get a blank screen.

Here is my template:

<script type="text/template" id="assessmentTitleTemplate">

    <div id="titleDiv">
        <label for="title">Title:</label> &nbsp;&nbsp;<input type="text" />
    </div>

    <div id="choicesDiv" style="display: none;">
        <label for="choices">Choices:</label><input type="text" />
    </div>

    <div id="typeDiv" style="display: none;">
        <label for="types">Types:</label>
        <select name="type">
            <option>red</option>
            <option>blue</option>
            <option>green</option>
        </select>
    </div>

   <div id="directionControl">       
        <input type="button" value="Prev" /> &nbsp;&nbsp;<input type="button" value="Next" />
    </div>

</script>

This is my backbone javascript code:

"use strict";

var titleView = Backbone.View.extend({
    tagName: 'div',
    className: 'title',
    template: _.template($('#assessmentTitleTemplate').html()),

    events: {
        'click .next': 'saveProceedNext',
        'click .prev': 'ProceedPrev'

    },

    initialize: function () {
        this.render;
    },

    render: function () {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    },

    saveProceedNext: function() {
        this.$('#titleDiv').hide();
        this.$('#choicesDiv').show();
    },

    ProceedPrev: function() {
    }
});

Solution

  • Your code is correct, but you're missing a couple of parens in your initialize body:

    initialize : function () {
        this.render();  // it was this.render; before
    }
    

    Your code isn't invoking the function.

    Also, you're missing class tags for your buttons, or else they won't work when clicked. Adding this will make them work:

    <input type="button" value="Prev" class="prev" /> &nbsp;&nbsp;<input type="button" value="Next" class="next" />
    

    Check this JSFiddle.