Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loading a knockout.js observableArray() from .ajax() call

Tags:

This puzzles me. It must be something small I'm not seeing. I'm trying to load a very simple observableArray in knockout with an ajax call.

javascript

// we bind the array to the view model property with an empty array.
var data = [];   
var viewModel = {
    vendors: ko.observableArray(data)
};
ko.applyBindings(viewModel);

$(function () {
    // on this click event, we popular the observable array
    $('#load').click(function () {
        // WORKS. Html is updated appropriately.
        viewModel.vendors([{ "Id": "01" },{ "Id": "02" },{ "Id": "03" }]);

        // DOES NOT WORK. Fiddler2 shows the same exact json string come back 
        // as in the example above, and the success function is being called.
        $.ajax({
            url: '/vendors/10',
            dataType: 'json',
            success: function (data) {
                viewModel.vendors(data);
            }
        });
    });
});

html

<button id="load">Load</button>
<ul data-bind="template: { foreach: vendors }">
    <li><span data-bind="text: Id"></span></li>
</ul>

Question: Why does the successful ajax call, who's data variable value matches byte-for-byte the hard typed value, not trigger the html refresh?

like image 895
one.beat.consumer Avatar asked Mar 16 '12 01:03

one.beat.consumer


People also ask

How do I get Knockout JS data?

prototype. loadNote = function (id) { var self = this; $. getJSON(uri + '/' + id, function (data) { self. note(data); }); }; // Apply bindings ko.

Can I make an Ajax call from JavaScript?

Ajax is a programming concept. Below are some ways to make Ajax call in JavaScript. Approach 1: In this approach, we will use the XMLHttpRequest object to make Ajax call. The XMLHttpRequest() method which create XMLHttpRequest object which is used to make request with server.

What activates knockout in JS?

To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.


1 Answers

There is no reason this would not work fine. As this demonstrates.

http://jsfiddle.net/madcapnmckay/EYueU/

I would check that the ajax post is actually returning json data and that that json is an array and that it's being parsed correctly.

I had to tweak the ajax call to get the fiddle ajax handlers to work correctly.

Nothing more I can think of.

Hope this helps.

like image 114
madcapnmckay Avatar answered Sep 28 '22 23:09

madcapnmckay