2013-10-06 137 views
0

我想加入如何在添加项目

事情后自动更新评论列表更新控制器动作后的观点是,我从emberjs样品开始与灯具和我已经修改了它,所以我可以得到当前数据在页面的开始。我已经添加了通过ajax添加评论功能,所有这些东西效果很好。现在我只是不知道如何在添加新的评论后自动出现。

这是我的应用程序代码:

window.Comments = Ember.Application.create(); 

Comments.Comment = DS.Model.extend({ 
    content: DS.attr('string') 
}); 

Comments.ApplicationController = Ember.ArrayController.extend({ 
rootElement: "#out", 
actions: { 
    createComment: function() { 
     var title = $('#new-comment').val(); 
     if (!title.trim()) { return; } 
     var comment = this.store.createRecord('comment', { 
      content: title 
     }); 
     this.set('newContent', ''); 
     comment.save(); 
    } 
} 
}); 

Comments.commentsView = Ember.View.extend({ 
id: 'com', 
layoutName: 'commentsTemplate', 
comments: null, 
init: function() { 
    console.log('init'); 
    var par = this; 
    $.ajax({ 
     url: "/getcomments", 
     type: "GET", 
     success: function(data) { 
      par.set("comments", data); 
     } 
    }); 
} 
}); 

,这我的模板

<div id="out"></div> 

    <script type="text/x-handlebars"> 
    <div class="container"> 
     <div class="row"> 
      <div class="col-xs-6"> 
       {{#view Comments.commentsView}}{{/view}} 
      </div> 
     </div> 
    </div> 
    </script> 


    <script type="text/x-handlebars" data-template-name="commentsTemplate"> 
    {{#each comment in view.comments}} 
     <div class="well"> 
      <b>{{comment.content}}</b> 
     </div> 
    {{/each}} 
    <br /> 
    {{input type="text" id="new-comment" placeholder="What you want to say?" value=newContent action="createComment"}} 
    </script> 

BTW。我有var title = $('#new-comment').val();原因this.get('newContent')是返回未定义的值,所以我不得不做一些事情来得到它使用原始JSON请求一次工作

+0

当挂钩烬与您的数据存储,更新列表会自动地创建一个新的记录时完成! – phoet

+0

@phoet你是什么意思?我以为我已经这样做了:/ – Fixus

+0

就像@Ivan说的,使用商店! – phoet

回答

1

您正在使用商店创建并保存新的评论,但是从服务器取您的视图comments财产在初始化期间。

显然,您还需要使用商店来检索评论。在这种情况下,您的集合将自动更新视图。

它应该是在控制器通过约定:

Comments.ApplicationController = Ember.ArrayController.extend({ 
    rootElement: "#out", 
    content: null, 

    loadComments: function() { 
    this.set('content', this.store.find('comment')) 
    }, 

    init: function() { this.loadComments(); this._super() } 

顺便说一句,评论甚至会保存前说:我真的不功能一样。为了避免这种情况,我们可以过滤我们的看法(不知道确切的语法):

persisted: function() { 
    this.get('content').filterBy('isNew', false) 
    }.property('content') // or .observes('[email protected]') i'm not sure