【问题标题】:Ember Data Push vs UpdateEmber 数据推送与更新
【发布时间】:2014-11-19 05:17:34
【问题描述】:

当我从服务器收到规范化数据时,我经常需要在存储中获取它。 Ember Data 对此具有语义“推送”:

var thing=normalizedThing
controller.store.push("thing",normalizedThing)

如果我需要更新现有记录,我可以使用 update:

var updatedThing=normalizedUpdatedThing
controller.store.push("thing",normalizedUpdatedThing)

但是,我发现即使存储中还没有加载记录,更新也会起作用;即在这种情况下它会像推动一样。但是,如果记录已经存在,则推送不会像更新一样。实际上它会抛出一个错误。所以我的问题是,推送的目的是什么?当希望使用标准化数据添加/更新存储时,我可以安全地调用 update 吗?还是我应该执行以下操作?

var thing=normalizedThing
if(controller.store.getById("thing",normalizedThing.get("id")){
  controller.store.update("thing",normalizedThing)
}else{
  controller.store.push("thing",normalizedThing)
}

【问题讨论】:

    标签: ember.js ember-data


    【解决方案1】:

    push 的目的是将完整的记录加载到存储中,而update 的目的是推送部分记录。所以push 如果您想完全替换一条记录,可能会删除属性,这很有用。因此,假设您的商店中有以下记录:

    {
        "id": 1,
        "name": "Bob",
        "status": "Going to the movies today!"
    }
    

    现在您还需要将以下 JSON 加载到商店中:

    {
        "id": 1,
        "name": "Bob"
    }
    

    如果您使用push,您将以没有状态的用户结束我们。如果您使用update,则用户将具有与以前相同的状态。您想要哪一个取决于您的用例,但同时拥有 pushupdate 可以让您选择其中任何一个。

    对我来说,push 的意义在于完全替换一条记录,而不必担心update 引起的潜在合并冲突。

    【讨论】:

      【解决方案2】:

      看源码https://github.com/emberjs/data/blob/master/addon/-private/system/store.js#L1680

      push => 
      _pushInternalModel => 
      _load => 
      _internalModelForId [This find or creates a model] => 
      internal-model#setupData
      
        setupData: function(data) {
          var changedKeys = this._changedKeys(data.attributes);
          merge(this._data, data.attributes);
          this.pushedData();
          if (this.record) {
            this.record._notifyProperties(changedKeys);
          }
          this.didInitalizeData();
        },
      

      所以看起来推送不会覆盖任何现有数据。并且看到不再有更新,我猜它们是相同的并且已被合并。 http://emberjs.com/api/data/classes/DS.Store.html#method_push

      【讨论】:

        猜你喜欢
        • 2014-06-08
        • 2023-04-01
        • 2015-11-17
        • 1970-01-01
        • 2018-01-14
        • 2023-03-25
        • 2016-10-15
        • 1970-01-01
        • 2015-02-11
        相关资源
        最近更新 更多