Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When changing the model for a view, is it better to replace the model or create a new view?

Tags:

backbone.js

I have an email view in my Backbone app. It's currently instantiated in the view action of my controller. It goes a little like this:

routes: {
  'email/:id': email
},

//...

email: function (id) {
  var email = new Email({
    id: id
  });
  this.emailView = new EmailView({
    model: email
  });
  email.fetch();
}

Now, the problem is, if I visit one email, then another, I end up creating two separate EmailViews. This means that, for example, the delete link in the EmailView is bound to two separate Email models, so clicking delete will delete both (not a good thing).

I'm looking at two solutions. In one, I'd cache the EmailView, and update its model. The problem then is that I'd have to re-bind the events in EmailView.

The other solution would be to create a new EmailView as I am at the moment, but unbind the old EmailView.el's events before replacing it.

Am I going about this the right way? Is there a better way to handle this situation? Cheers in advance.

like image 321
Skilldrick Avatar asked Jul 28 '11 12:07

Skilldrick


People also ask

How do you change the model in drawing Creo?

If both the old and new models are from the same family, Right mouse button in the field of the drawing, pick properties, drawing models then replace. If the models are not from a family table, then bring up the new model up with the drawing not in session.


1 Answers

Create a separate view instance for each model instance. Each time you visit a new email then throw away the the old view and create a new view with the new email instance.

Probably what you have if I am guessing is a list view on the left hand side and an editor on the right. You select the email from the list on the left and you want the email body to appear on the right.

You really want about 5 view classes.

PageView
    has_one EmailCollectionView on left
    has_one EmailEditorView on right

EmailCollectionView
    has_many EmailSummaryViews as vertical list

EmailEditorView
    has_one EmailView centered

When you click in the EmailCollectionView you trigger an event which is picked up by EmailEditorView which throws away it's old instance of EmailView and renders a new version of EmailView

Something like that anyway

like image 94
bradgonesurfing Avatar answered Oct 04 '22 05:10

bradgonesurfing