在模板中的$ data上获得两种方式的绑定 [英] Getting two way binding on $data inside a template

查看:83
本文介绍了在模板中的$ data上获得两种方式的绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置通用的Knockout模板,这些模板可以根据数据类型在编辑和只读模式之间切换.如果您曾经使用过ASP.NET的动态数据:就像它们的字段模板一样.例如:

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>

这是这样使用的:

<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"示例中那样在字段级别使用模板,而不是显式的元素/控件.这样一来,整个表格就可以轻松地在编辑和阅读模式之间切换,而无需包含大部分重复的标记.这也允许重复使用常见的数据类型编辑/显示标记,例如对日期字段使用日期选择器等.

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.

问题
模板内的$data伪变量没有双向绑定.它将在可观察值中反映当前值,但是输入控件中的更改不会设置该值.

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.

如何在$data上进行双向绑定?

How can I get two way binding on $data?

另请参见此jsfiddle

推荐答案

最简单的选择是将一个对象传递给模板绑定,该模板绑定允许您访问实际的可观察对象,例如:

The simplest choice is to pass an object to the template binding that allows you to access the actual observable like:

template: { name: 'text', data: {field: name} }

然后,在模板中绑定字段"而不是"$ data".

Then, bind against "field" instead of "$data" in your template.

要考虑的另一件事是使用函数确定模板,然后可以使用单独的模板进行编辑/查看,例如:
http://www.knockmeout.net/2011/03/quick-tip-dynamically- changes.html

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

这篇关于在模板中的$ data上获得两种方式的绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆