Search code examples
ember.jsember-dataember-model

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


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?


Solution

  • 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.