How do I get the unique id of ember object when object is initialized?

匆匆过客 提交于 2019-12-12 03:40:44

问题


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


回答1:


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();
  }
});


来源:https://stackoverflow.com/questions/40628814/how-do-i-get-the-unique-id-of-ember-object-when-object-is-initialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!