samedi 23 avril 2016

Ember Data usage without a Backend API and converting Models to JSON (Ember 2.5.0)

I am using Ember v2.5.0 without an external datastore.

After creating a record at the route using the createRecord method it cannot be queried for in other parts of the app (controller or components).

My understanding is that I need to use store.push to save the record locally so that it may be accessed by the controller. However the store.push method requires the arguments to be in json format.

I could just do away with the models however I was wondering if there a quick way to convert the models into json format using Ember version 2.5.0? I would also like to know if my assumptions on using store.push to persist the data locally is a recommended way to go when using Ember Data without an external backend.

There are other references on "Ember models to json" on stack overflow however they are outdated and I particularly would like to know if my approach/assumptions are correct and if not, what the alternatives are. Im very new to Ember.

Problem

//Route
import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        let shape, square;

        square = this.store.createRecord('square');

        shape = this.store.createRecord('shape', {
            shared: 'shared-value',
            square: square
        });

        return shape;
    }
});

//Controller
import Ember from 'ember';

export default Ember.Controller.extend({
    actions: {
        someActionName() {
            console.log(this.store.peekRecord('shape', 1)); //undefined!
        }
    }
});

//Shape Model
import DS from 'ember-data';

export default DS.Model.extend({
    shared: DS.attr('string', { defaultValue: '' }),
    square: DS.belongsTo('square')
});

//Square Model
import DS from 'ember-data';

export default DS.Model.extend({
    sides: DS.attr('string', { defaultValue: '4' }),
    whereIbelong: DS.belongsTo('shape')
});



Aucun commentaire:

Enregistrer un commentaire