Ember.js: save the entry in Ember.Data, wait for an answer before displaying

I am creating an application that allows users to post to Twitter. When they click the submit button, we close the posting form. We create a Message object that is stored in the data warehouse and sent to the server. The server creates a Post object, then sends the request to Twitter. Then the server updates the Post object, returns the updated information back to the user interface.

This part is already working. But I need to know if it does not work, so that I can warn the user that their message has not passed, and keep an open publication form. Here are some localized details about my application.

Social.Message = DS.Model.extend({ text: DS.attr("string"), created: DS.attr("date"), isPending: DS.attr("boolean"), posts: DS.hasMany("Social.Post") }); Social.Post = DS.Model.extend({ text: DS.attr("string"), status: DS.attr("string"), created: DS.attr("date"), message: DS.belongsTo("Social.Message"), msgStatus: function() { return ((this.get('status') === 'S') ? true : false); }.property('status') }); 

The life cycle of a message (status) goes from P (waiting) to Q (in line) to S (sent), E (error) is also the opportunity and status that I'm really looking for. Here's the saveMessage method:

 saveMessage: function(text){ var acct = Social.Account.find(this.get("id")), msg = Social.store.createRecord( Social.Message, { text: text, created: new Date() } ); acct.get("messages").addObject(msg); Social.store.commit(); Ember.run.later(this, function() { msg.get('posts').forEach(function(p){ p.reload(); }); }, 1000); } 

You can see that I pause for a second to make the server work, and then try to reload the Post object with the response from Twitter. Those last few lines where I think this new code will go, but I'm not sure how to listen to something that might not come back. I would rather not "wait" a second, instead it would be nice if the message could just be updated. Not sure how to do this.

Thoughts?

+4
source share
2 answers

You need to run your code as a callback after creating the entry. Here's how to do it:

 msg.one('didCreate', function() { // transition to new route showing data just created }); Social.store.commit(); 

This will add a one-time call to the record when it is created. There is also "didUpdate" and "didDelete". You need to add these callbacks before create is called (obviously).

I am not sure how to handle the error condition, as I have not yet studied this.

Edit: this is actually broken, for https://github.com/emberjs/data/issues/405 , so waiting may be the only option for now.

+3
source

It looks like you don't want the two-way data binding to be here, and one-way access might be useful to you. Here's a great blog on a full-length blog that explains this in a bit more detail.

http://www.solitr.com/blog/2012/06/ember-input-field-with-save-button/

0
source

Source: https://habr.com/ru/post/1469061/


All Articles