2012-08-02 66 views
3

在我的index.html,我有以下模板为什么这个Ember.TextArea没有绑定到控制器内容?

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

预先感谢您

回答

4

我会做的反而是有结合的内容和返回的所有消息的集合的一系列一个计算属性,我将绑定textarea。

喜欢的东西:

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

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

    return messages; 

}.property('[email protected]') 

,并在您的模板:

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

我认为这个属性应该在'content。@ each'上计算,所以当插入一条新消息时它会被重新评估。 – 2012-08-02 15:57:01

+0

不会在这种情况下valueBinding =“消息”?因为内容是数组和消息是我们的自定义监听器 – 2012-08-02 17:27:38

+0

@ sly7_7感谢您的更正!确实更有意义 – 2012-08-03 21:52:33

2

它采取了共同努力来自@ShaiRez和@ sly7_7所以我想在这里包括最后的工作液

<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('[email protected]') 
    }); 
+1

仅供参考,我认为这是一个优化版本:http://jsfiddle.net/Sly7/U9j9f/它不会在每次更改时迭代内容,但会附加最后一条消息。 请注意,您应该使用get()方法来访问每个您想要访问的对象的属性。 – 2012-08-02 23:43:51

+0

不错的改进!现在如果只有我可以让你回答所有的答案,所以我可以给你一些代表:) – 2012-08-03 00:52:07

+2

不要担心:),我不是一个代表猎人。重要的是我们学到了东西:) – 2012-08-03 06:44:14

相关问题