vendredi 18 septembre 2015

pushObject not parsing JSON to Ember object

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}}




Aucun commentaire:

Enregistrer un commentaire