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>
source share