2
votes

Is it possible to applyBindings when the dataModel of the viewModel is unknown? My problem is that the dataModel structure is first known after an ajax call on the page and the way i understand knockout.js is that the viewModel should be inistialized on page load?

The code fails with nCustomerId is undefined.

How should i handle this? I could wait with calling the ko.applyBindings() until i know the dataModel structure (which i do after the ajax call), but is that the right way to do it when using knockout.js?

function initModel () {
var kunderModel = function () {
    var self = this;
    self.list = ko.observableArray();
    self.selectedItem = ko.observable();
    self.newItem = ko.observable();  

    self.add = function () {
        self.selectedItem(newItem(self.newItem));
        showInputContainer();
    };

    self.getList = function () {
        var nButikId = jQuery("#butikid").val();
        jQuery.ajax({
            url: "crm_service.wso/Dan_Butik_Kunder_Tabel/JSON/",
            data: { nButikId: nButikId },
            success: function (data) {
                self.list(data);
            },
            complete: function () {
                connectExt.UIElements().Loading(false);
            }
        });
    }
}
}

    _viewModel = new kunderModel();
    ko.applyBindings(_viewModel);

    jQuery(document).ready(function () {
        initModel();
    });

<div data-bind="template: { name: 'editTmpl', data: selectedItem }"></div>

<script id="editTmpl" type="text/html">      
    <div  class="opretContainer">
        <div class="opretContainerTitle">
            <span data-bind="visible: nCustomerId == 0">New</span>
            <span data-bind="visible: nCustomerId != 0">Edit</span>
        </div>
    </div>
</script>
1
Just do it after the AJAX call. - Alnitak

1 Answers

7
votes

you do not need the initFuction. What you should do is initialize the _viewModel directly in the JQuery document callback.

You have to understand that your ViewModel itself is already a function. You can call your getList function directly inside your viewmodel when it is initialized.

What I would do:

jQuery(document).ready(function () {
    _viewModel = new kunderModel();
    ko.applyBindings(_viewModel);    
});

and than inside kunderModel:

var kunderModel = function () {
   var self = this;
   self.list = ko.observableArray();

   self.getList = function () {
       var nButikId = jQuery("#butikid").val();
       jQuery.ajax({ ... });
   };

   self.getList();
}

This way the getList method gets invoked at the end of the creation of the ViewModel. (I think of it as a method which is invoked by the "constructor". Since everything is observable, when the callback is executed, your UI will be automatically updated.