Pattern binding does not work when source is null / undefined

Can someone explain to me what is wrong with my model or view template in this jsfiddle example ?

It does not work as expected. Basically, the view model contains an object and this object is null . In the view, there is a template binding to this object. Since this object is null, it should not display a template. However, it tries to display the template and does not work in my example. If the job object is null, I do not want to display the template.

According to this article of Ryan , if the viewmodel contains a null object and there is a binding <<21> for this object, it will not display the template.

Here is my model:

 var job = function(title) { this.jobTitle = ko.observable(title); } var ViewModel = function(first, last) { this.firstName = ko.observable(first); this.lastName = ko.observable(last); //this.job = ko.observable(new job("software developer")); this.job = ko.observable(null); this.fullName = ko.computed(function() { return this.firstName() + " " + this.lastName(); }, this); }; ko.applyBindings(new ViewModel("FirstName", "LastName")); 

And this is the view:

 <div class='liveExample'> <p>First name: <input data-bind='value: firstName' /></p> <p>Last name: <input data-bind='value: lastName' /></p> <p data-bind="template: { name: 'editorTmpl', data: job }"></p> <h2>Hello, <span data-bind='text: fullName'> </span>!</h2> </div> <script id="editorTmpl" type="text/html"> Job: <input data-bind='value: jobTitle' /> </script> 
+6
source share
2 answers

related art ... was written almost 3 years ago. By the time the latest version of Knockout was around 1.2.1.

And in Knockout 1.2.1, your code works fine: Demo using KO 1.2.1

However, Knockout has changed a lot since then, so it no longer supports this behavior.

Currently, you need to use the if template binding option

 <p data-bind="template: { name: 'editorTmpl', if: job, data: job}"></p> 

JSFiddle demo.

Or binding with ( if ) to achieve the same result:

 <div class='liveExample'> <p>First name: <input data-bind='value: firstName' /></p> <p>Last name: <input data-bind='value: lastName' /></p> <!-- ko with: job --> <p data-bind="template: { name: 'editorTmpl'}"></p> <!-- /ko --> <h2>Hello, <span data-bind='text: fullName'> </span>!</h2> </div> 

JSFiddle demo.

+7
source

You can combine the binding of your template with a div that uses the "if" data binding to the observed job:

 <div data-bind="if: job"> <p data-bind="template: { name: 'editorTmpl', data: job }"></p> </div> 

The editor template is hidden when the job is null and visible when it is not null.

EDIT:

The best solution is to pass the "if" option of the template binding:

 <p data-bind="template: { if: job, name: 'editorTmpl', data: job }"></p> 
+3
source

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


All Articles