Can anyone explain me what is wrong with my view model or template in this example jsfiddle?
It doesn't work as expected. Basically the view model contains an object and that object is null. In the view, there is a template binding to this object. As this object is null, it shouldn't render the template. However, it does try to render the template and fails in my example. If job object is null then I don't want to render the template.
According to this article by Ryan, if a viewmodel contains a null object and there is a "template binding" for this object, it won't render the template.
Here is my view 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>