在模板内对 $data 进行双向绑定
我正在尝试设置通用的 Knockout 模板,可以根据数据类型在编辑和只读模式之间切换。如果您曾经使用过 ASP.NET 的动态数据:它就像它们的字段模板。例如:
<script type="text/html" id="text">
<!-- ko if: $root.editable -->
<input type="text" data-bind="value: $data" />
<!-- /ko -->
<!-- ko ifnot: $root.editable -->
<span data-bind="text: $data"></span>
<!-- /ko -->
</script>
其使用方式如下:
<label><input type="checkbox" data-bind="checked: editable" /> Editable</label>
<p>Name: <input data-bind="value: name" /></p>
<p>Name2: <span data-bind="template: { name: 'text', data: name }"></span></p>
使用以下视图模型:
var viewModel = {
name: ko.observable("Brian"),
editable: ko.observable(true)
};
这个想法是能够像“Name2”示例中那样在字段级别使用模板,而不是显式元素/控件。这使得整个表单可以在编辑和阅读模式之间轻松切换,而无需大段大部分重复的标记。这还允许重用常见数据类型编辑/显示标记,例如对日期字段使用日期选择器等。
问题
模板内的 $data
伪变量没有双向绑定。它将反映可观察值中的当前值,但输入控件的更改不会设置该值。
如何在 $data
上进行双向绑定?
另请参阅这个jsfiddle
I am trying to setup generic Knockout templates that can be toggled between edit and readonly mode based on data type. If you've ever used ASP.NET's dynamic data: it's like their field templates. For example:
<script type="text/html" id="text">
<!-- ko if: $root.editable -->
<input type="text" data-bind="value: $data" />
<!-- /ko -->
<!-- ko ifnot: $root.editable -->
<span data-bind="text: $data"></span>
<!-- /ko -->
</script>
This is used like this:
<label><input type="checkbox" data-bind="checked: editable" /> Editable</label>
<p>Name: <input data-bind="value: name" /></p>
<p>Name2: <span data-bind="template: { name: 'text', data: name }"></span></p>
With the following view model:
var viewModel = {
name: ko.observable("Brian"),
editable: ko.observable(true)
};
The idea is to be able to use templates at the field level like in the "Name2" example, instead of explicit elements/controls. This allows entire forms to be easily toggled between edit and read mode without having large sections of mostly duplicated markup. This also allows reuse of common data type editing/display markup, for example using datepickers for date fields, etc.
The Problem
The $data
pseudo variable inside the template does not have two way binding. It will reflect the current value in the observable, but changes in the input control will not set the value.
How can I get two way binding on $data
?
See also this jsfiddle
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单的选择是将一个对象传递给模板绑定,该对象允许您访问实际的可观察对象,例如:
然后,绑定模板中的“field”而不是“$data”。
另一件需要考虑的事情是使用函数来确定您的模板,然后您可以使用单独的模板进行编辑/查看,例如:
http://www.knockmeout.net/2011/03/quick-tip-dynamically-改变.html
The simplest choice is to pass an object to the template binding that allows you to access the actual observable like:
Then, bind against "field" instead of "$data" in your template.
Another thing to consider would be using a function to determine your template, then you can use separate templates for edit/view like:
http://www.knockmeout.net/2011/03/quick-tip-dynamically-changing.html