29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Underpinning the Ajax functions is the model, which I defined like this:<br />

...<br />

var model = {<br />

reservations: ko.observableArray()<br />

};<br />

...<br />

Knockout works by creating observable objects that it monitors for changes and uses to update the HTML displayed by the<br />

browser. My model is simple. It consists of an observable array, which is just like a regular JavaScript array, but is wired up so<br />

that any changes I made are detected by Knockout. You can see how I use the model in the Ajax functions, like this:<br />

...<br />

function getAllItems() {<br />

sendAjaxRequest("GET", function(data) {<br />

model.reservations.removeAll();<br />

for (var i = 0; i < data.length; i++) {<br />

model.reservations.push(data[i]);<br />

}<br />

});<br />

}<br />

...<br />

The two statements I highlighted are how I get the data from the server into the model. I call the removeAll method to<br />

remove any existing data from the observable array and then iterate through the results I get from the server with the push<br />

method to populate the array with the new data.<br />

Defining the Bindings<br />

Knockout applies changes in the data model to HTML elements via data bindings. Here are the most important data bindings in the<br />

Index view:<br />

...<br />

<br />

<br />

<br />

<br />

<br />

<br />

Remove<br />

<br />

<br />

<br />

...<br />

Knockout is expressed using the data-bind attribute and there is a wide range of bindings available, three of which I have<br />

used in the view. The basic format for a data-bind attribute is:<br />

data-bind="type: expression"<br />

The types of the three bindings in the listing are foreach, text and click, and I picked these three because they<br />

represent the different ways in which Knockout can be used.<br />

The first two, the foreach and text bindings, generate HTML elements and content from the data model. When the<br />

foreach binding is applied to an element, Knockout generates the child elements for each object in the expression, just like the<br />

Razor @foreach that I was using in the partial view.<br />

720

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!