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?

    1. The with bending beside setting the binding context also handles the case when the value is null or undefinied.

      From the documentation

      If the expression you supply evaluates to null or undefined descendant elements will not be bound at all, but will instead be removed from the document.

      If you don’t want to use the with you have to handle the null or undefinied case “by hand ” so you can only call name() if the selectedItem() returned something.

      This can be done with the statement selectedItem() && selectedItem().name(). (null, the empty string and undefinied evaluates to false evertying else is to true.)

      So the following binding is working:

      
      

      Demo JSFiddle.

    Originally posted 2013-11-09 22:47:10.