knockout.js - Template binding not working when source is null/undefined -
can explain me wrong view model or template in this example jsfiddle?
it doesn't work expected. view model contains object , object null
. in view, there template binding object. object null, shouldn't render template. however, try render template , fails in example. if job object null don't want render template.
according this article ryan, if viewmodel contains null object , there "template
binding" object, won't render template.
here 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 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>
the linked artifice written 3 years ago. time latest version of knockout around 1.2.1.
and in knockout 1.2.1 code working fine: demo using ko 1.2.1
however since knockout has changed lot not supporting behavior anymore.
nowadays need use if
option of template binding
<p data-bind="template: { name: 'editortmpl', if: job, data: job}"></p>
demo jsfiddle.
or with
(if
) binding achieve same outcome:
<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>
demo jsfiddle.
Comments
Post a Comment