Irfan Y
Irfan Y

Reputation: 1300

Prevent html loading before data loading in knockout mapping

HTML:

<div id="knockoutBinding">
    <div class="toolbar" data-bind="template: 'user-portfolio-entry' "></div>
</div>

<script id="user-portfolio-entry" type="text/html">
<!-- ko if: vm.currentPortfolioEntry().hasOwnProperty('Step') -->
//other stuff
<!-- /ko -->
</script>

JavaScript:

var UserPortfolioViewModel = function () {
        var self = this;

        self.currentPortfolioEntry = ko.observable(null);
        $.ajax({
            type: "POST",
            url: getPortfolioEntryUrl,
            data: JSON.stringify(data1),
            dataType: "json",
            contentType: "application/json",
            success: function (response) {
                self.currentPortfolioEntry(ko.mapping.fromJS(response));
            },
            error: function (data) {
                alert("fail");
            }
        });
}
var vm;
    $(function () {
         vm = new UserPortfolioViewModel();
         ko.applyBindings(vm, $("#knockoutBinding")[0]);
    });

I get error:

Uncaught TypeError: Unable to process binding "template: function (){return 'user-portfolio-entry' }" Message: Unable to process binding "if: function (){return vm.currentPortfolioEntry().hasOwnProperty('Step') }" Message: Cannot read property 'hasOwnProperty' of null

and when the line in ajax success is executed self.currentPortfolioEntry(ko.mapping.fromJS(response)); then I can see the value of vm.currentPortfolioEntry().hasOwnProperty('Step') in console but at that time html had finished loading and I can't get data in html.

How to load the html after the success of ajax, so that properties can be mapped. Or any other way to tackle this error?

Upvotes: 0

Views: 212

Answers (1)

Serge K.
Serge K.

Reputation: 5323

You could refactor your if to test if the variable exits like following :

<!-- ko if:  vm.currentPortfolioEntry() && vm.currentPortfolioEntry().hasOwnProperty('Step') -->

Upvotes: 2

Related Questions