简答
双向绑定:通常所有与用户可以直接更改的内容相关的绑定,无需特殊脚本的帮助,例如表单控件值或状态:value、hasFocus、textInput、@ 987654325@,selectedOptions。或者任何与用户可以更改的内容相关的自定义绑定(5 个可点击星的典型示例,实现为 ko 自定义绑定)。
单向绑定:用户不能直接改变的所有状态,例如visible。用户无法直接更改可见性:必须通过脚本完成。在这种情况下,脚本不应更改 DOM 元素本身的可见性,而应更改绑定的 observable。第一个不会更新 observable,但后者会更新绑定元素的可见性。
长答案
如果您了解如何实现自定义绑定,您将了解它们的工作原理:Creating custom bindings:
ko.bindingHandlers.yourBindingName = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// This will be called when the binding is first applied to an element
// Set up any initial state, event handlers, etc. here
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// This will be called once when the binding is first applied to an element,
// and again whenever any observables/computeds that are accessed change
// Update the DOM element based on the supplied values here.
}
};
如果您进一步观察,您会看到init 回调可以用于什么:
Knockout 将为您使用绑定的每个 DOM 元素调用一次 init 函数。 init 主要有两个用途:
1.为DOM元素设置任何初始状态
- 注册任何事件处理程序,例如,当用户单击或修改 DOM 元素时,您可以更改关联的 observable 的状态
关键在第二点:如果绑定处理了某种事件,它会修改可观察值,也就是你认为的“双向绑定”的“回归”。
因此,任何处理事件以更新 observable 的绑定都是“双向”绑定。