commadelimited
commadelimited

Reputation: 5119

Ember.Data reloading content, UI not updating

We're using Ember.Data rev 11. Our relationships are like so:

Social.Account = DS.Model.extend({
    name: DS.attr("string"),
    username: DS.attr("string"),
    messages: DS.hasMany("Social.Message"),
});

Social.Message = DS.Model.extend({
    text: DS.attr("string"),
    created: DS.attr("date"),
    account: DS.belongsTo("Social.Account"),
    posts: DS.hasMany("Social.Post")
});

Social.Post = DS.Model.extend({
    text: DS.attr("string"),
    created: DS.attr("date"),
    message: DS.belongsTo("Social.Message"),
});

A user creates a Message which can then be sent to multiple social media accounts, each of which results in a Post. On submit a Message and Post record are created, but we information in the Post record that we get back from Twitter. The code we're currently using looks like this:

saveMessage: function(text){
    var acct = Social.Account.find(this.get("id")),
        msg = Social.store.createRecord(
                    Social.Message,
                    {
                        text: text,
                        account: acct,
                        created: new Date()
                    }
                );

    acct.get("messages").addObject(msg);
    Social.store.commit();

    msg.addObserver('id', this, function(){
        var timeoutID = window.setTimeout(function(){
            msg.reload();
            console.log('reloading');
        }, 5000);
    });

}

As soon as I hit submit the Message and Post both load in the UI. Problem is that the Post is missing he native_url property, which can only be gotten after the http request to Twitter is made. The weird thing is that if I replace the contents of the addObserver call with an alert window, the native_url value pops into place. I'mt not sure why but it does.

Anyway, so my question is what do I have to do to get the Post object to update with data from the server, AND update the UI with that new data.

Upvotes: 2

Views: 1429

Answers (1)

Peter Wagenet
Peter Wagenet

Reputation: 5056

I can't guarantee that this is the solution without seeing all of you code. But one thing you should do is not rely on setTimeout for Ember callbacks. Instead, use Ember.run.later.

Ember.run.later(this, function() {
    this.reload();
    console.log('reloading');
}, 5000);

Anything that happens asynchronously outside of Ember should be wrapped in a RunLoop. So, in the event that your callback is part of a plugin or something else along those lines, you can also wrap it all in Ember.run.

Upvotes: 2

Related Questions