Backbone.View:删除与不同模型相关的不同视图

Backbone.View: Delete different views related to different models

本文关键字:视图 模型 View 删除 Backbone      更新时间:2023-09-26

我需要显示与three different model或集合相关的three different views
为了执行此任务,我编写了以下代码。(*)
请告诉我这是否是正确的方法,无论如何它有效。

这是我的问题。
在其中一个视图中,假设firstView ,可以对服务器执行DELETE request,该服务器会注意删除与此three view相关的所有数据。

现在我需要删除我的三个视图...但从firstView我无法访问其他两种观点。

1) 如何执行此任务?
2) 我应该重新设计/改进我的实现吗?


(*)

// module for display three different views
define([
    "js/views/01View",
    "js/views/02View",
    "js/views/03View"
], function (FirstView, SecondView, ThirdView) {
    var MainView = Backbone.View.extend({
        initialize: function ()
        {
            this.render();
        },
        render: function ()
        {
            var movie_id = this.options.movie_id;
            this.firstView = new FirstView(movie_id);
            this.secondView = new SecondView(movie_id);
            this.thirdView = new ThirdView(movie_id);
        }
    });    
    return MainView;
});

附言:

_id用于构建集合或模型的 url 参数

url1: http://localhost/movie/movie_id   (model1)
url2: http://localhost/movie/movie_id/followers   (collection2)
ulrs: http://localhost/movie/movie_id/feeds (collection3)

当我删除模型 1 时,应该删除与集合 2 和集合 3 相关的视图 2 和视图 3。

为了根据我们的评论对话解决您的问题,Backbone 架构使用事件,所以为什么不使用事件聚合器来发送事件,不要将自己限制在主干结构上。 在主干中将事件从一个视图触发到另一个视图 此模式为您的问题提供了一个优雅的解决方案。

Views不应响应直接方法调用,而应响应事件。说你要么创建一个可以从每个视图访问的通用EventAggregator(正如@20100在他的答案中所解释的那样),要么你通过一个通用模型连接视图,并使每个视图都听自己更有趣的事件。

在您的情况下,您可以从视图实例化中实例化 Movie 模型,并连接它周围的三个视图:

// code simplified and not tested
var MainView = Backbone.View.extend({
  initialize: function ( opts ) {
    this.movie = new Movie({ id: this.opts.movie_id} )
    this.movie.fetch();
    this.render();
  },
  render: function () {
    this.firstView = new FirstView( this.movie );
    this.secondView = new SecondView( this.movie );
    this.thirdView = new ThirdView( this.movie );
  }
});
var ThirdView = Backbone.View.extend({
  initialize: function( opts ) {
    this.movie = opts.movie;
    this.movie.on( "destroy", this.cleanUp, this )
    this.followers = // fetch the followers as you do now, use this.model.id
  }
  cleanUp: function(){
    // your clean up code when model is detroyed
  }
});