我为 Ember-Data 编写了一个自定义适配器,用于Rhom API。
这是代码:
'use strict';
DS.RhomAdapter = DS.Adapter.extend(Ember.Evented, {
extractVars: function(rhomRecord) {
return rhomRecord.vars();
},
objectToId: function(record) {
record["id"] = record.object;
return Ember.copy(record);
},
find: function(store, type, id) {
console.log('find');
var record = Rho.ORM.getModel(this.model).find(
'first',
{
conditions: {object: id}
}
);
var result = record.vars();
result["id"] = result.object;
return Ember.RSVP.resolve(result);
},
findAll: function(store, type) {
console.log('findALl');
var records = Rho.ORM.getModel(this.model).find('all');
var results = records.map(this.extractVars);
var results = results.map(this.objectToId);
var promise = new Ember.RSVP.Promise(function(resolve, reject){
// succeed
resolve(results);
// or reject
reject([]);
});
return promise;
},
createRecord: function(store, type, record) {
Rho.ORM.getModel(this.model).create(record.toJSON());
return Ember.RSVP.resolve();
},
updateRecord: function(store, type, record) {
console.log(record.get('id'));
var result = Rho.ORM.getModel(this.model).find('first', {conditions: {object: record.get('id')}});
result.updateAttributes(record.toJSON());
return Ember.RSVP.resolve();
},
deleteRecord: function(store, type, record) {
var result = Rho.ORM.getModel(this.model).find('first', {conditions: {object: record.get('id')}});
result.destroy();
return Ember.RSVP.resolve();
}
});
创建新记录时,会调用 createRecord。但是 Ember 不知道创建的对象的 id。现在,当我尝试在视图中修改该对象时,会调用 updateRecord 并传递该对象,但该对象没有 ID。那么,如果我不知道 ID,如何更新后端呢?