knockout.js - Do I have to use the knockout with binding? -
i'm new knockout , trying understand how of bindings should work.
i thought reference child observable in normal binding without need cannot working.
my model , view model are;
model = function(name) { this.name = ko.observable(name); }; viewmodel = function () { var list = ko.observablearray([new model("apple"), new model("pear")]), selecteditem = ko.observable(); function selectitem(item) { selecteditem(item); } return { list: list, selecteditem: selecteditem, selectitem: selectitem }; };
and here bindings:
<div id="content"> <ul id="list" data-bind="foreach: list"> <li data-bind="text: name, click: $parent.selectitem"></li> </ul> </div> <p>will show selected item</p> <div data-bind="with: selecteditem"> <span data-bind="text: name"></span> </div> <div> <p>won't show selected item</p> <span data-bind="text: selecteditem().name()"></span> </div>
alternatively working fiddle here.
as far understood should able see value selecteditem().name
apply bindings throwing error, works if div has with: selecteditem
binding.
do have no optin use with
binding in type of scenario?
the with
bending beside setting binding context handles case when value null
or undefinied
.
from documentation
if expression supply evaluates
null
orundefined
descendant elements not bound @ all, instead removed document.
if don't want use with
have handle null
or undefinied
case "by hand " can call name()
if selecteditem()
returned something.
this can done statement selecteditem() && selecteditem().name()
. (null
, empty string , undefinied
evaluates false
evertying else true
.)
so following binding working:
<span data-bind="text: selecteditem() && selecteditem().name()"></span>
demo jsfiddle.
Comments
Post a Comment