Ember-Data定制适配器

时间:2013-10-08 13:47:21

标签: ember.js ember-data

我为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,如何更新后端?

1 个答案:

答案 0 :(得分:1)

createRecord返回的承诺应该使用新记录(包括id)解决。

createRecord: function(store, type, record) {
    var json = record.toJSON();
    Rho.ORM.getModel(this.model).create(record.toJSON());
    json.id = .... 
    return Ember.RSVP.resolve(json);
},