daveycroqet
daveycroqet

Reputation: 2727

Knockout bindings from JSON file

What am I doing wrong with my bindings? I simply get [object HTMLElement] returned for each one.

Please note this is a pared-down version and I will be wanting to access the full range of the JSON values.

Fiddle:

https://jsfiddle.net/0416f0s7/2/

Code:

<div data-bind="text: intro"></div>

function ViewModel(stories) {
    var self = this;
    self.stories = ko.observableArray(ko.utils.arrayMap(stories, function(story) {
        return story.stories;
    }));
};

$.getJSON('data.json', function(data) {
    window.storyViewModel = new ViewModel(data.stories);
    ko.applyBindings(window.storyViewModel);
});

JSON (filename data.json):

{
    "stories": [
        {
            "intro": "Hi",
            "outro": "Bye",
            "elements": [
                {
                    "title": "Title 1",
                    "image": "img/image1.jpg",
                    "paragraph": "Wordswordswords"
                },
                {
                    "title": "Title 2",
                    "image": "img/image2.jpg",
                    "paragraph": "More wordswordswords"
                }
            ]
        }
    ]
}

Upvotes: 0

Views: 64

Answers (1)

Syam Kumar
Syam Kumar

Reputation: 373

Your html change to

`<div data-bind="foreach:stories">
        <div data-bind="text: intro"></div>
    </div>

your code change to

  function test(stories) {
        var self = this;
        self.stories = ko.observableArray(ko.utils.arrayMap(stories, function (story) {
            return story;
        }));

    }

Upvotes: 2

Related Questions