Vimal
Vimal

Reputation: 35

Convert javascript array to ko.observablearray and bind to template

I want to convert a javascript array that is in data.js file to ko.observable array and bind it to list tag

HTML

<script type="text/html" id="profileListTemplate">
        <li>
            <strong data-bind="text: name"></strong>            
        </li>
    </script>

   <h1>Profile Viewer</h1>

    <div class="tabbable tabs-left" id="profilesTabViewer">
        <ul class="nav nav-tabs" id="profileTab" data-bind="template: { name: 'profileListTemplate'}">
        </ul>
        <div class="tab-content" id="profileContent">
        </div>
    </div>`

data.js

    var data = [
    {
     'id': '1',
     'firstName': 'Megan',
     'lastName': 'Fox',
     'picture': 'images/01.jpg',
     'bio': 'Megan Denise Fox was born May 16, 1986 in Rockwood, Tennessee. ... 
    },
    ....
    ];

Upvotes: 2

Views: 9493

Answers (3)

Simon LeVasseur
Simon LeVasseur

Reputation: 422

Plain and simple:

var myObservableArray = ko.observableArray(data);

Here is your updated JSFiddle: http://jsfiddle.net/simonlevasseur/qr7PL/

Note that in your template, you shouldn't put: people.firstName It should just be firstName as explained here: http://knockoutjs.com/documentation/foreach-binding.html

Upvotes: 6

user3174746
user3174746

Reputation:

Why not simply this:

var list = ko.observableArray(data);

I use this approach when building an underlying array. I then push the underlying all at once. Another construct might be:

var list = ko.observableArray([]);
list.push(data);

But, you may need to make each property observable, in which case you could use the Knockout mapping plugin as gaurav suggests, or you could simply write your own mapper. A good example of how to do that can be found in John Papa's course from Pluralsight: Single Page Apps with HTML5, Web API, Knockout and jQuery.

Upvotes: 2

Gaurav
Gaurav

Reputation: 8487

You can use fromJSON function of knockout which will convert JSON string to object. In your scenario you can do something like:

//converting your json string to array of objects
var list = ko.fromJSON(data); 

//creating observable array from array of objects.
var observableList = ko.observableArray(list);  

You should check knockout mapping plugin also.

Upvotes: 0

Related Questions