Reputation: 1516
I want to push data to my model. This model has an array of object called content. The problem is that Ember does not parse it into an Ember object even if I use the pushObject method. This results in my template not updating. Here is the code of the request :
Ember.$.ajax({
type: 'POST',
url: 'conversations/' + self.get('model').id + '/send',
dataType: 'json',
data: new_message,
success: function(data){
self.get('model.content.sentMessages').pushObject(data);
},
error: function(){
}
});
How do you parse JSON response into an ember object?
EDIT : I am using ember-data
App.Conversation = DS.Model.extend({
status: DS.attr(),
readStatus: DS.attr(),
timeAgoElement: DS.attr(),
lastMessage: DS.attr(),
customer: DS.belongsTo('customer'),
user: DS.belongsTo('user'),
content: DS.attr(),
lastReopenedSlug: DS.attr(),
lastReopened: function(){
return this.get('lastReopenedSlug') === this.get('id');
}.property('lastReopenedSlug', 'id'),
sortedContent: function(){
if(this.get('content')){
var content = this.get('content');
return Ember.ArrayProxy.createWithMixins(Ember.SortableMixin, {
sortProperties: ['createdAt'],
sortAscending: true,
content: content.sentMessages.concat(content.receivedMessages).concat(content.notes).concat(content.assignations).concat(content.statuses)
});
}
}.property('content'),
timeAgoFormated: function(){
return moment(this.get('timeAgoElement')).fromNow();
}.property('timeAgoElement'),
lastMessageFormated: function(){
var lastMessage = this.get('lastMessage');
if(nthOccurrence(lastMessage, ' ', 3) != -1){
return lastMessage.substr(0, nthOccurrence(lastMessage, ' ', 3)) + "...";
}
return lastMessage;
}.property('lastMessage')
});
The data returned to the template is the sortedContent, which depends on the content. I noticed that my new data is pushed to the content as I want, but in JSON format instead of Ember Object format, which prevents my template from updating.
Useful template rendering :
{{#each elem in model.sortedContent}}
--display x--
{{/each}}
Upvotes: 0
Views: 516
Reputation: 1110
You're pushing data into content.sentMessages
but the model.sortedContent
property is only looking at content
before it recomputes. You might need to also add content.sentMessages.length
to your sortedContent
property -
sortedContent: function() {
if (this.get('content')) {
var content = this.get('content');
return Ember.ArrayProxy.createWithMixins(Ember.SortableMixin, {
sortProperties: ['createdAt'],
sortAscending: true,
content: content.sentMessages.concat(content.receivedMessages).concat(content.notes).concat(content.assignations).concat(content.statuses)
});
}
}.property('content', 'content.sentMessages.length')
Does that work? Also maybe throw a console.log('whatever')
in sortedContent:
to see if it's being called when you do your .pushObject()
Upvotes: 1