Dan Ray
Dan Ray

Reputation: 21893

Why is my backbone view render putting "undefined" at the top?

Most of the render function in the following view is irrelevant, I think but I'm leaving it for completeness. I'm stepping through a list of workflow steps, noting switching the class of the li depending on various states of the thing.

var WorkStepView = Backbone.View.extend({
    className: "workflowStep",

    render: function() {
        var output;
        var arrowPlaced = false;
        var self = this;
        i = 0;
        _.each(this.collection.models, function(s) {
            var post = "";
            var classname = '';
            if (s.attributes["complete"] != 1) {
                if (! arrowPlaced) {
                    classname = "current";
                    if (s.attributes["adminCompletable"] == 1 ) {
                        post = ' - <input onClick="completeStep(' + i + ');" type="button" value="Completed" />';
                    }
                    arrowPlaced = true;
                }
                else {
                    classname = "future";
                }
            }
            else {
                classname = "past";
            }
            output += '<li class="' + classname + '">' +  s.attributes["description"] + post + '</li>';
            i++;
        });
        this.el.innerHTML = output;
        return this;
    },
});

When the user selects an asset from a list elsewhere on the page, it brings up a bunch of data including this stuff. An asset "has" a workflow, which "has" many steps. The step data is stored in window.Steps, and then this is called:

function populateSteps() {
    window.workStepLists = new WorkStepView({
        collection: window.Steps,
        el: $('#workflowSteps')[0],
    });
    workStepLists.render();
}

But then I get this:
enter image description here

There's this extraneous "undefined" up there at the top of the list. It wasn't there before fetching and rendering this model. I don't know what's up with that at all.

Help?

Upvotes: 0

Views: 438

Answers (1)

Brian Genisio
Brian Genisio

Reputation: 48137

You are not initializing output to be anything. So, output += "foo" becomes "undefinedfoo".

Simply initialize your output variable with an empty string:

var output = '';

Upvotes: 3

Related Questions