Domanda

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);

È stato utile?

Soluzione

i had to use

homeSummaryViewModel = ko.mapping.fromJS(result);

instead of

homeSummaryViewModel = ko.mapping.fromJSON(result);

Altri suggerimenti

The value binding is only for form-input elements; you need to be using the text binding.

The problem is you binding with the $.get, I created a simple test case http://jsfiddle.net/PB9KL/, it works fine.

var homeSummaryViewModel;
getHomeSummaryViewModel();


function getHomeSummaryViewModel() {

            homeSummaryViewModel = ko.mapping.fromJSON('{"Level":"Noob","Score":788}');

            ko.applyBindings(homeSummaryViewModel,document.getElementById("homeSummary"));

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top