Getting two-way binding to $ data inside a template

I am trying to set up general knockout patterns that can be switched between edit mode and readonly based on data type. If you've ever used ASP.NET dynamic data: it's like their field patterns. For instance:

<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 as follows:

 <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 field-level templates, as in the "Name2" example, instead of explicit controls / controls. This makes it easy to switch whole forms between edit and read modes without large sections, mostly duplicated markups. It also allows you to reuse the common edit / display type of the data type, for example, using datepickers for date fields, etc.

Problem
The $data pseudo-variable inside the template has no two-way binding. It will display the current value in observable, but changes to input control will not set the value.

How to get two-way binding to $data ?

See also this jsfiddle

+6
source share
1 answer

The easiest choice is to pass an object to the template binding, which allows you to access the actual observable, for example:

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

Then bind to the "field" instead of the "$ data" in your template.

Another thing to consider is to use a function to define your template, then you can use separate templates for editing / viewing, for example:
http://www.knockmeout.net/2011/03/quick-tip-dynamically-changing.html

+7
source

Source: https://habr.com/ru/post/906764/


All Articles