简体   繁体   中英

Backbone render view multiple times

I have a backbone.js app where I have a view like:

var StoreView = Backbone.View.extend({
el: ".container",
initialize: function() {
    this.render();
},

events: {
    "click #addProduct": "addProduct",
},

render: function() {
    this.$el.html(render("index"));
},

addProduct: function(){
    var productView = new StoreProductView({
        el: $('#products')
    });
    productView.render();
}
});

and my StoreProductView looks like:

var StoreProductView = Backbone.View.extend({
render: function () {

    this.$el.html(render("products/product"));

    return this;
}
});

So when I click #addProduct, a new StoreProductView template is called. But if you hit #addProduct again, nothing happens. How can I get it so that for each time #addProduct is hit, a new StoreProductView is rendered? So if I hit it x number of times, there is x StoreProductView s?

you need to change this line:

this.$el.html(render("products/product"));

to this for example:

this.$el.append(render("products/product"));

because every time you substitute the html and nw you don't append, only remove html content and insert the new one. With append() you can add anoter product.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM