2

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

Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90

1 Answers1

2

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>
Anders
  • 17,306
  • 10
  • 76
  • 144
  • can you give a with example. In your Github link i cant see "with" example – Suresh Kamrushi Apr 02 '13 at 08:33
  • after download only i find runner.html rest all the files are js. and i do not understand runner.html – Suresh Kamrushi Apr 02 '13 at 09:41
  • All you need is the file under src, runner.html is just a file to run the unit tests. Include the src file and then your set, you can use the examples under the Github wiki to get you started – Anders Apr 02 '13 at 10:13