为什么这个Ember.TextArea没有绑定到控制器内容?

时间:2012-08-02 15:09:15

标签: ember.js

在我的index.html中,我有以下模板

<script type="text/x-handlebars">
    {{#with ChatApp.messagesController}}
      {{view Ember.TextArea valueBinding="content.message" rows="12" cols="70"}}
    {{/with}}
  </script>

我的消息模型看起来像这样

ChatApp.Message = Ember.Object.extend({
  message: null
});

我的消息视图和控制器看起来像这样

ChatApp.messagesView = Ember.View.extend({});

ChatApp.messagesController = Ember.ArrayController.create({                                                                                           
  content: [],
  text: '',
  sendMessage: function() {
    var newChatText = this.get('text');
    socket.emit('sendchat', newChatText);
  },
  updateChat: function(username, text) {
    var controller = this;
    var content = this.get('content');
    var newMessage = ChatApp.Message.create({ message: text });

    content.push(newMessage);
    console.log("update " + controller.get('content'));
    controller.set('content', content);
  }
});

我可以在console.log中看到,每次更新时,另一个模型对象都被添加到内容中,但文本区域没有被更新

这是jsFiddle网址http://jsfiddle.net/eDfKJ/

提前谢谢

2 个答案:

答案 0 :(得分:4)

我要做的是拥有一个绑定到内容的计算属性,并返回所有消息的聚合字符串,然后将textarea绑定到该字符串。

类似的东西:

messages: function() {
    var content = this.get('content');
    var messages = "";

    ... loop the content and combine the messages string... 

    return messages;

}.property('content.@each')

并在您的模板中:

  <script type="text/x-handlebars">
    {{#with ChatApp.messagesController}}
      {{view Ember.TextArea valueBinding="content.messages" rows="12" cols="70"}}
    {{/with}}
  </script>

答案 1 :(得分:2)

@ShaiRez和@ sly7_7共同努力,所以我想在这里加入FINAL工作解决方案

<script type="text/x-handlebars">
    {{#with ChatApp.messagesController}}
      {{view Ember.TextArea valueBinding="messages" rows="12" cols="70"}}                                                                                                            
    {{/with}}
  </script>

ChatApp.messagesController = Ember.ArrayController.create({
  content: [],
  text: '',
  sendMessage: function() {
    var x = this.get('text');
    socket.emit('sendchat', x);
  },    
  updateChat: function(username, text) {
    var controller = this;
    var newMessage = ChatApp.Message.create({ message: text });
    controller.content.pushObject(newMessage);
  },
  messages: function() {
    var content = this.get('content');
    var messages = "";
    for(i = 0; i < content.length; i++) {                                                                                                                                            
      messages += content[i].message                                                                                                                                                 
      messages += '\n';
    }
    return messages;
  }.property('content.@each')
  });