How can I load a model and immediately have access to it

194 views Asked by At

Say that when I load the page I include a json hash of the current user's info

in an injection I load the info:

user_data = JSON.parse(user_json)
App.Model.load(user_data['id'], user_data)
container.typeInjection('controller', 'currentUser', 'controller:currentUser')
App.set('currentUserController', controller)

But I'd like to set the value of that currentUserController right here as well - App.Model.load doesn't return the actual model instance!

to get it, I need to run App.Model.find(user_data['id']) and because this is done at start up, it seems that ember-model always ends up querying the database for this model rather than using the json I've preloaded.

Because I use this model in the startup of my app I can't defer the loading - how can I get access to the loaded model without needing to do an ajax request?

2

There are 2 answers

0
gone On BEST ANSWER

I'm using Ember-model so this might be different for ember-data.

The trick is to use create (not create record!) to make an empty version of the model, and then populate it with the instance's load call. IE

            user = App.User.create()
            user.load(user_data['id'], user_data)

That will both load the data into the version you have, and correctly call didLoad to ensure it's in the store.

1
Yossi Shasho On

This answer might help you: https://stackoverflow.com/a/16254735/437019

And as for loading from json, try:

var store = DS.get("defaultStore");
var adapter = store.adapterForType(App.User);
var id = USER_ID_HERE;
adapter.didFindRecord(store, App.User, YOUR_JSON_DATA_HERE, id);
var user = App.User.find(id);