【问题标题】:How to handle multiple backbone model changes in one handler如何在一个处理程序中处理多个主干模型更改
【发布时间】:2014-02-06 12:26:29
【问题描述】:

我在主干中有一个视图和一个与之关联的模型。查看模型更改并相应更改其显示区域。例如:

var Part = Bacbone.Model.extends({
  defaults:{
    partId = null,
    manufacturer: null,
    manufactureDate: null,
    type: null
  }
});

var PartsCollection = Backbone.Collection.extends({
   model:Part;
)};

var Car = Backbone.Model.extends({
   defaults:{
       carModel: null,
       carName: null,
       color: null,
       partsCollection: null
   },  
   //Overwite the parse method to fill partsCollection
   parse: function(response){
       // creating partsCollection from response and adding an attribute
       // response.partsCollection = new PartsCollection();
       retrun response;
   }
});

我有一个类似上图的结构。在我的设计策略中,我会在模型更改时更改视图内容。

所以现在,例如,如果我在 5000 个零件中的 1000 个零件中将制造商“A”替换为制造商“B”。这应该修改我的视图,为此我正在我的视图中监听模型更改事件。由于 1000 个零件修改,将触发 1000 个更改事件。

由于制造商更改,我可能还想更改零件模型的“manufacturerDate”属性,如果我也更改“manufacturerDate”属性,这又会触发另外 1000 个事件。

在我看来,处理这么多事件可能不是一个好主意,这就是我的感受。那么有谁能给我建议一下解决这个问题的方法

【问题讨论】:

  • 你完全错了!为什么要同时进行 1000 次更改?!最终用户是否在一个地方看到所有这些?我用 todomvc (1000+ todos) 编写了一个非常繁重的测试,并提出了 angularjs 在这种情况下比其他人快得多的想法。我还为这个案例启动了一个项目(Lilith.js,还没有准备好快速的主干分支,你仍然可以从中获得想法!)。顺便说一句,我可以推荐 3 个选项:使用 react.js 或其他框架,根据您的需要使用其他绑定方法或库,不要做 1000 次更改!

标签: backbone.js marionette backbone-events backbone-model


【解决方案1】:

我不知道这是否是正确的方法,但我提供了以下解决方案。不要在 CarView 中直接监听 Part 模型的变化。而是在 CarView 中为汽车模型 this.model.partsCollection 中的集合添加 change:manufacturer 事件的侦听器。在集合上添加一个 API changeManufacturer,接受一系列零件(或零件 ID)和新的制造商详细信息。 API 将更新零件制造商并触发事件 change:manufacturer 任何想要在镜头中更改零件制造商的代码都将使用集合 API changeManufacturer,CarView 可以监听事件 change:manufacturer 并自行更新。

var CarView = Backbone.View.extend({
    initialize: function() {
        // do other stuffs
        this.listenTo(this.model.partsCollection, "change:manufaturer", manufacturereChanged);

    },

    manufacturereChanged: function(arrOfChangedParts) {
        // you now have all changed parts array
        // process as your logic
    }
});


var PartsCollection = Backbone.Collection.extend({
   model: Part,
   changeManufacturer: function(arrPartIds, newManfacturerDetails) {
      var arrChangedModels = [];
      // iterate over ids
          // get the model and change manufacturer info in model
          // add changed model to arrChangedModels
      // ends loop

      // once all models are changed trigger an event "change:manufacturer"
      this.trigger('change:manufacturer', arrChangedModels)
   }
});

【讨论】:

    【解决方案2】:

    Collection 具有与其模型相同的侦听更改的能力,此外还有更多选项可以识别与以前的集合和新值的差异。

    理想情况下,一个触发器应该可以很好地使用 n 项更新视图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      相关资源
      最近更新 更多