当改变模型视图,是它更好地更换模型或创建一个新的看法? [英] When changing the model for a view, is it better to replace the model or create a new view?

查看:67
本文介绍了当改变模型视图,是它更好地更换模型或创建一个新的看法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序骨干的邮件视图。目前它实例中的视图我的控制器的作用。它去有点像这样:

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();
}

现在的问题是,如果我访问一个电子邮件,然后又我最终创建了两个单独 EmailView 秒。这意味着,例如,在 EmailView 绑定到两个独立的电子邮件机型的删除链接,所以单击删除将同时删除(不是一件好事)。

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).

我看两种解决方案。在一个,我会在缓存 EmailView ,并更新其模式。接着的问题是,我不得不重新绑定在 EmailView 事件

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.

其他的解决方案是创建一个新的 EmailView ,因为我的那一刻,但解除旧 EmailView.el 的事件。

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.

推荐答案

我认为DOM事件处理程序应当由该视图的remove()的调用方法进行去除 - 看的 http://api.jquery.com/remove (盖下调用骨干)

I think that the DOM event handlers should be removed by a call to the view's remove() method - see http://api.jquery.com/remove (which Backbone calls under the covers)

如果您覆盖remove()方法也除去结合为JohnnyO建议任何模型事件,垃圾收集应该采取移除视图的照顾。

If you override the remove() method to also remove binding to any model events as JohnnyO suggested, garbage collection should take care of removing the view.

我落得这样做覆盖remove()方法来处理这​​个问题:

I ended up doing overriding the remove() method to handle this:

class EmailView extends Backbone.View
    initialize: () ->
        @model.bind('change', @render)
    render: () =>
        # do some stuff
    remove: () ->
        @model.unbind('change', @render)
        super()

您可以这样在路由器然后使用:

You can then use as such in a Router:

    routes:
      'email/:id': email

    //...

    email: (id) ->
      var email = new Email({
        id: id
      });
      this.emailView.remove() if this.emailView 
      this.emailView = new EmailView({
        model: email
      });
      email.fetch();
    }

这将工作假设视图中的所有事件都绑定到正确的元素 - 也就是说,你在视图以及每个视图中使用@el(或this.el)有自己的@ EL /本.el。

This will work assuming that all events in the view are bound to the correct element - that is, that you're using @el (or this.el) in the View and that each view has its own @el/this.el.

这篇关于当改变模型视图,是它更好地更换模型或创建一个新的看法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆