How to use the mapping plugin for knockout?

Ranjith Ramachandra picture Ranjith Ramachandra · Mar 29, 2012 · Viewed 7.4k times · Source

I have written the following code

$(function() {



    function get_updates () {
        $.getJSON('/new-lines.json', function(data) {
            var fullViewModel= ko.mapping.fromJS(data);
            ko.applyBindings(fullViewModel)


        });
    }

    function poll()
    {
        setTimeout(function(){
        get_updates();
        poll();},3000)

    }




    poll()
});

And the JSON data looks like this:

{"state": "R", "qualities": ["ABC", "XYZ", "324"], "name": "ABC"}

How should I write the html part?

I am very new to javascript. Please help.

Answer

madcapnmckay picture madcapnmckay · Mar 30, 2012

Your question is a little misleading since you seem to be using the mapping plugin correctly.

What is not correct is the way you are using knockout. You are polling every 3 seconds, loading data and then rebinding. It is recommended that you only called applyBindings once for a typical KO application.

If you are updating a model periodically your approach of using the mapping plugin is correct. Here's how I'd do it.

http://jsfiddle.net/madcapnmckay/NCn8c/

$(function() {
    var fakeGetJSON = function () {
        return {"state": "R", "qualities": ["ABC", "XYZ", "324"], "name": "ABC"};
    };

    var viewModel = function (config) {
        var self = this;

        // initial call to mapping to create the object properties
        ko.mapping.fromJS(config, {}, self);

        this.get_updates = function () {
            ko.mapping.fromJS(fakeGetJSON(), {}, self);
        };            
    };

    // create viewmodel with default structure so the properties are created by
    // the mapping plugin
    var vm = new viewModel({ state: "M", qualities: [], name: "Foo" });

    function poll()
    {
        setTimeout(function(){
            vm.get_updates();
            poll();
        }, 3000)
    }

    // only one call to applybindings        
    ko.applyBindings(vm);
    poll();
});

And an example html

<h1>Name <span data-bind="text: name"></span></h1>
<h2>State <span data-bind="text: state"></span></h2>
<ul data-bind="foreach: qualities">
    <li data-bind="text: $data"></li>
</ul>

Hope this helps.