Trouble inserting to DOM child views in Backbone.j

2019-07-31 08:52发布

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条回答
孤傲高冷的网名
2楼-- · 2019-07-31 09:08

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;
    }
});
查看更多
登录 后发表回答