Do I have to use the knockout with binding?-Collection of common programming errors
I’m fairly new to knockout and trying to understand how some of the bindings should work.
I thought that I could reference a child observable in a normal binding without the need for with but I cannot get it working.
My model and 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 are the bindings:
        
        
    
    
Will show selected item
    
        
    
    
        
Won't show selected item
        
    
Alternatively a working fiddle is here.
As far as I understood I should be able to see a value for selectedItem().name but the apply bindings is throwing an error, however it works perfectly if the div has the with: selectedItem binding.
Do I have no optin but to use the with binding in this type of scenario?
- 
The withbending beside setting the binding context also handles the case when the value isnullorundefinied.From the documentation If the expression you supply evaluates to nullorundefineddescendant elements will not be bound at all, but will instead be removed from the document.If you don’t want to use the withyou have to handle thenullorundefiniedcase “by hand ” so you can only callname()if theselectedItem()returned something.This can be done with the statement selectedItem() && selectedItem().name(). (null, the empty string andundefiniedevaluates tofalseevertying else is totrue.)So the following binding is working: Demo JSFiddle. 
Originally posted 2013-11-09 22:47:10.