消息模型
function MessageModel(content) {
var self = this;
self.content = content;
}
房间 View 模型
self.currentMessage = ko.observable(new MessageModel(""));
self.addMessage = function () {
self.messages.push(self.currentMessage());
self.currentMessage(new MessageModel(""));
};
查看
<form data-bind="submit: addMessage">
<input data-bind='value: currentMessage.content, valueUpdate: "afterkeydown"' />
<button id="ButtonSendMessage" type="submit">Send</button>
</form>
当用户在输入框中键入时希望更新当前消息内容属性,当我单击添加时我希望为 currentMessage 添加内容。但是内容总是空白。
最佳答案
可能是因为 content 不是一个可观察的并且值绑定(bind)是错误的,因为 currentMessage
是一个可观察的所以绑定(bind)你的任何属性必须像 currentMessage().prop
或在元素上下文中使用 with: currentMessage
绑定(bind),尝试如下操作:
function MessageModel(content) {
var self = this;
self.content = ko.observable(content);
}
我还建议您使用 textInput
绑定(bind):
<form data-bind="submit: addMessage">
<input type="text" data-bind='textInput: currentMessage().content' />
<button id="ButtonSendMessage" type="submit">Send</button>
</form>
textInput Binding:
The textInput binding links a text box () or text area () with a viewmodel property, providing two-way updates between the viewmodel property and the element’s value. Unlike the value binding, textInput provides instant updates from the DOM for all types of user input, including autocomplete, drag-and-drop, and clipboard events.
Ref:TextInput Bind
关于javascript - 如何将当前对象绑定(bind)到文本输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34257271/