Henry
Henry

Reputation: 32915

Life cycle of a backbone.js view, a few beginner questions

Can someone please explain, what is the life cycle of a View (controller), say, for a Row in a TODO list app?

App.RowView = Backbone.View.extend({
    events:{
        "click #del" : "delRow"
    }
});

Most of the tutorials, the AppView would do this:

    render: function()
    {
        this.collection.each(this.renderRow, this);
        return this;
    },
    renderRow: function(row)
    {
        var rowView = new App.RowView({model:element});
        this.$('#rows').append(rowView.render().el);
    }

Questions:

  1. does that mean rowView is only used once and disposed in renderRow()? Or does it live on?
  2. if true, when to kill the View? is adding listener to model.destroy and invoke remove() at the view good enough?
  3. If I already have the row's markup rendered from the server, would the click #del events still get captured and do something w/o a rowView created?
  4. shouldn't 'click #del' be better located in the parent view, so that jQuery can delegate and attach behavior there?
  5. does that mean I have 1 rowView per row? wouldn't that mean the _.template is being compiled on every row? any alternative?

Upvotes: 1

Views: 2375

Answers (1)

fguillen
fguillen

Reputation: 38888

  1. The reference dies, the View can remain if there are other references pointing to it.
  2. You kill the View when is not needed any more, normally when is not visible any more. If your View is binding any event you have to unbinding them before call remove(): Pattern to manage views in backbone
  3. An instance of RowView have to be instantiated for the event to be captured.
  4. This depends on the behavior you are looking for, but in your example I think each View has to capture each own click #del event, if you declare the event in the parent View how do you know wich row to delete?
  5. Normally you declare the template in the View definition and you assign a compiled version of it to this.template like this: template: _.template( "hello: <%= name %>" );.

Upvotes: 2

Related Questions