pushObject没有将JSON解析为Ember对象

时间:2015-09-18 20:35:04

标签: ember.js ember-data

我想将数据推送到我的模型。该模型具有一个称为内容的对象数组。问题是,即使我使用pushObject方法,Ember也不会将其解析为Ember对象。这导致我的模板不更新。以下是请求的代码:

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(){

    }
  });

如何将JSON响应解析为ember对象?

编辑:我正在使用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')
});

返回给模板的数据是sortedContent,它取决于内容。我注意到我的新数据被推送到我想要的内容,但是采用JSON格式而不是Ember Object格式,这会阻止我的模板更新。

有用的模板渲染:

{{#each elem in model.sortedContent}}
    --display x--
{{/each}}

1 个答案:

答案 0 :(得分:1)

您正在将数据推送到content.sentMessages,但model.sortedContent属性仅在重新计算之前查看content。您可能还需要将content.sentMessages.length添加到sortedContent属性 -

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')

这有用吗?也可以在console.log('whatever')中抛出sortedContent:,看看当你执行.pushObject()

时它是否被调用