Question

I am very new to Knockout and trying to explore it. I know how to use foreach but confuse about "with". I just gone through the documentation of knockout (http://knockoutjs.com/documentation/with-binding.html) for With. still like:

1) when should i used "with"

2) With is alternative for foreach?

3) is there any difference between "with" and foreach

Thanks in Advace

Was it helpful?

Solution

1) A with is a inline template binding, its commonly used when you want to hide a area when a sub ViewModel is null, its also good practice to use it when you want to change the context from the parent model to the sub model.

2) Not really, with works with any object. If your array can be null then with is good (I cant remember from top of my head if foreach binding works with null values)

3) Yes, they are totally different. With gives no array foreach template functionallity if you want to use with with a array then you need to use a foreach binding inside your with.

Also have a look at my Convention over configuration library, it takes away all headaches about bindings, here is a with example

https://github.com/AndersMalmgren/Knockout.BindingConventions/wiki/With-convention

edit: My library abstracts the with binding, the example in the above Github link would look like this without my convention library

<select data-bind="options: items, value: selectedItem, optionsText: 'name', optionsCaption: 'Select...'"></select>

<div data-bind="with: selectedItem">
    <span data-bind="text: name"></span>
</div>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top