Industrial
Industrial

Reputation: 42758

Backbone.js views & parent elements

Does it make sense to let a backbone.js-view know about it's parent element, when you have a simple view containing very little logic, or is it bad practice?

Like this:

var BooklistRow = Backbone.View.extend({
    tagName: "li",
    parent: "#booklist",

    render: function() {
        $(this.el).html("<b>" + this.model.get("title") + "</b>");
        $(this.parent).append(this.el);
        return this;
    }
});  

Upvotes: 0

Views: 2589

Answers (1)

Paul Hoenecke
Paul Hoenecke

Reputation: 5060

It is better if a view knows nothing outside of itself. This will make it more reusable.

Also in your example, you are adding to the parent on render. At some point, you may want to re-render the BooklistRow after it is already appended to the parent.

I think it is better for the parent to render and add the children:

var Booklist = Backbone.View.extend({
tagName: "ul",

render: function() {
    // maybe should remove existing books here first
    this.model.each(this.addOneBook);
    return this;
},
addOneBook: function(book) {
   var view = new BooklistRow({
     model: book
   });
   $(this.el).append(view.render().el);}});

Now, if a single book changes, it can re-render itself without the list even knowing.

Upvotes: 2

Related Questions