More about observable arrays in Knockoutjs

Surendran Sukumaran

1 min read

ObservableArray is a nice way to update a collection in Knockoutjs, if we want to repeat certain UI sections like name of the products to get the desired html output we can use Observablearray along with foreach.
Lets see them now.

Expected output :
[source language=”html”]

  • iPhone
  • Samsung Galaxy
  • Nokia Lumia

[/source]
We use foreach to loop through a section of markup for each entry in an array.
[source language=”html”]

[/source]
Here is the script to update values in the html.
[source language=”javascript”]

[/source]
So when the page loads we are not assigning any values to the products, we just keep it as empty array.
When we run this in browser we can see a single list with no values.
Okay so let’s hide that list if the products array size is not greater than 0
[source language=”ruby”]
data-bind=”visible: products().length > 0
[/source]
The item will be visible only if “products().length > 0″
This is how the actual html will look like.
[source language=”html”]

    [/source]
    Now try it in the browser, oh nice the list isn’t appearing.
    Our next job would be filling up a list of products with observable array.
    We can have a products_list array of hashes which has the “product_name” as the key and a value for it.
    [source language=”javascript”]

    [/source]
    Let’s have a link, once we click on the link we will fill the products.
    [source language=”ruby”]
    Fill Products
    [/source]
    We are adding a click event for this link which will call the fillProducts products method, where we gonna update the products UI
    So the final js code would look like this
    [source language=”javascript”]

    [/source]
    Now run this in the browser, Wow.
    You will see the products list filled with values.My next blog would be about nested observablearray.

    Related posts:

    Leave a Reply

    Your email address will not be published. Required fields are marked *