javascript - 如何将当前对象绑定(bind)到文本输入?

标签 javascript knockout.js

消息模型

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/

相关文章:

javascript - 为什么我的 viewModel 不工作

javascript - Moment.js 只能使用一次

javascript - then block 中出现意外标记

javascript - canvas.toDataURL() 无法正常工作

json - knockout JS : how to set the initial value from a dropdown list when data is retrieved asynchronously using JSON?

javascript - knockoutjs通过点击事件获取(真正绑定(bind)的)元素

knockout.js - removeAll vs在knockoutjs中使用[]清空数组

javascript - 正确的 KO 绑定(bind)来访问数组中的对象?

javascript - 按键触发方法

javascript - 如何仅在 react 文档的特定字段发生变化时才运行跟踪器计算?