Search code examples
javascriptjqueryknockout.jsknockout-mapping-plugin

Binding not working for Knockout, ReferenceError when ko.applybindings on specific element


I have this ajax to get the data

var homeSummaryViewModel;

$(document).ready(function () {
    getHomeSummaryViewModel();

});
function getHomeSummaryViewModel() {

    $.ajax({
        url: "/api/homeservice/get",
        type: "get",
        contentType: "application/json",
        success: function (result) {            
            homeSummaryViewModel = ko.mapping.fromJSON(result);

            ko.applyBindings(homeSummaryViewModel, $("#homeSummary").get(0));

        },
        error: function (result) {
            //handle the error, left for brevity
        }
    });
}   

Here is my html

        <div class="plan-name-bronze">
            <h4>Home</h4>
            <div class="icon">
                <i class="fa fa-trophy fa-5x"></i>
            </div>

        </div>
        <ul class=" text-left" id="homeSummary">
            <li class="plan-feature">Completed Level : <span data-bind="text: Level"></span> </li>                
            <li class="plan-feature">Total Score : <span data-bind="text: Score"></span> </li>
        </ul>
    </div>
</div>

Here is my JSON

{"Level":"Noob","Score":788}

I get this error below in knockout-3.0.0.debug.js, when id do homeSummaryViewModel.peek() i get null. i see the data is sent from server in firebug as show above JSOn Data, ko.mapping does not throw error it just is not working maybe???

ReferenceError: Level is not defined return new Function("$context", "$element", functionBody);


Solution

  • i had to use

    homeSummaryViewModel = ko.mapping.fromJS(result);
    

    instead of

    homeSummaryViewModel = ko.mapping.fromJSON(result);