Trouble inserting to DOM child views in Backbone.j

2019-07-31 09:13发布

问题:

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();

回答1:

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;
    }
});