gpt4 book ai didi

javascript - find() 和 getById() 之间的 Ember 数据差异

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:25:00 25 4
gpt4 key购买 nike

我知道有一个问题名为:Ember data: what is difference between find and findById? .但是,如果我错了,请更正,但我认为它与旧版本的 Ember 数据有关,因为我在 embet-data doc 中找不到此方法。 .

我试图在我的目录中插入一个新类别。这行不通:

newRecord: function() {
catalog = this.store.find('catalog', 1);
record = this.store.createRecord( 'category', {category_name_fr_sh: 'Nouvelle categorie'});
catalog.get('catalog_categories_ids').pushObject(record);
this.set('content', record);
},

但是这项工作:

newRecord: function() {
catalog = this.store.getById('catalog', 1);
record = this.store.createRecord( 'category', {category_name_fr_sh: 'Nouvelle categorie'});
catalog.get('catalog_categories_ids').pushObject(record);
this.set('content', record);
},

医生说

Get a record by a given type and ID without triggering a fetch. This method will synchronously return the record if it's available. Otherwise, it will return null.

我真的不明白为什么“trggering the fetch”不起作用。我认为 find() 首先查看它是否在商店缓存中,只有在找不到它时才获取。谁能赐教一下?

最佳答案

this.store.find('catalog', 1); 不返回记录,它返回一个 DS.PromiseObject。因为,如果您的记录不在记录缓存中,则需要向服务器发出请求。如果记录已经加载,您仍然有 promise 对象,以保持相同的方法行为,但没有请求发送到服务器。

this.store.getById('catalog', 1); 从记录缓存中返回对象(如果存在)。之所以可行,是因为您已经使用 this.store.find('catalog');this.store.find('catalog', 1);

您可以使用 then 方法从 DS.PromiseObject 获取目录记录:

newRecord: function() {
var self = this;
var catalogPromise = this.store.find('catalog', 1);
catalogPromise.then(function(catalog) {
var record = this.store.createRecord( 'category', {category_name_fr_sh: 'Nouvelle categorie'});
catalog.get('catalog_categories_ids').pushObject(record);
self.set('content', record);
})
},

关于javascript - find() 和 getById() 之间的 Ember 数据差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20100447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com