bcm
bcm

Reputation: 5500

Trouble inserting to DOM child views in Backbone.js

Trying to get my child views (OfferMarketView) created from the forEach back into the DOM. What is the best way to do this? I can't get the below working.

// DEFINE VIEW
var OfferView = Backbone.View.extend({
    initialize: function () {
        this.model = new Offers();
        this.model.fetch();
        this.model.on('change', this.modelChange);
        this.model.on('change', this.render);
        this.modelChange = function () {
            alert('model changed');
        };
        this.render();
    },
    render: function () {
        var container = this.el;
        this.model.forEach(function (s) {
            var view = new OfferMarketView({
                id: "container" + s.get('name').toLowerCase().replace(/\s*/g, '')
            });
            $("#offerCol").append(view.el);
        });
        return this;
    }
});
var OfferMarketView = Backbone.View.extend({
    tagName: "div",
    className: "classname",
    events: {},
    render: function() {
    }
});


// INITIALISE VIEW
offerView = new OfferView();

Upvotes: 1

Views: 247

Answers (1)

Didier Ghys
Didier Ghys

Reputation: 30666

You have to render you view before appending the element:

$("#offerCol").append(view.render().el);

Note that you have to to add return this; in the render method so it is chainable:

var OfferMarketView = Backbone.View.extend({
    tagName: "div",
    className: "classname",
    events: {},
    render: function() {
        return this;
    }
});

Upvotes: 2

Related Questions