在初始化对象时,如何获取ember对象的唯一ID? [英] How do I get the unique id of ember object when object is initialized?

查看:125
本文介绍了在初始化对象时,如何获取ember对象的唯一ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用createRecord实例化了模型。现在如何在保存之前获取该记录的ID?

解决方案

您可以考虑 generateIdForRecord



http://emberjs.com/api/data/classes/DS.Adapter.html#method_generateIdForRecord


如果您的记录的全局唯一ID应在
客户端上生成,请执行generateIdForRecord()方法。此方法将在每次创建新记录时调用
,并从其返回的
将被分配给记录的primaryKey。



大多数传统的类REST REST API不会使用这种方法。
相反,记录的ID将由服务器设置,当
适配器调用
didCreateRecord()时,您的
适配器将使用新的ID更新存储。如果您打算在客户端生成
生成记录ID,则仅实现此方法。


您甚至可以创建模型适配器说 post model,你可以创建 post 适配器并覆盖 generateIdForRecord 方法。



适配器/ post.js

 code>从./application导入ApplicationAdapter; 
从ember-data导入DS;来自'uuid'的
import {v4};

导出默认ApplicationAdapter.extend({
generateIdForRecord:function(store,inputProperties){
return v4();
}
});


I have instantiated the model using createRecord. Now how do I get the id of that record before it is saved ?

解决方案

You can consider the generateIdForRecord

http://emberjs.com/api/data/classes/DS.Adapter.html#method_generateIdForRecord

If the globally unique IDs for your records should be generated on the client, implement the generateIdForRecord() method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record's primaryKey.

Most traditional REST-like HTTP APIs will not use this method. Instead, the ID of the record will be set by the server, and your adapter will update the store with the new ID when it calls didCreateRecord(). Only implement this method if you intend to generate record IDs on the client-side.

You can even create model specific adapter say post model, you can create post adapter and override generateIdForRecord method.

adapters/post.js

import ApplicationAdapter from './application';
import DS from 'ember-data';
import { v4 } from 'uuid';

export default ApplicationAdapter.extend({
  generateIdForRecord: function(store, inputProperties) {
    return v4();
  }
});

这篇关于在初始化对象时,如何获取ember对象的唯一ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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