1

Edit Looks like I got it loading from the server now. If anyone sees any issues with this, would love to hear about them.

Having some issues getting the knockout mapping plugin working. I can get this working with static data with no problems, see http://jsfiddle.net/RH9wQ/

When I try to load in data from the server, it doesn't seem to work, though. Below is the bare bones code I'm using. The data in the jsfiddle is the exact data that's being returned from my server. Am I missing something completely obvious?

What I'm doing is loading in different drugs based on alpha buttons that are clicked. So click on "y" and get a list of drugs that start with y, click on "z" and get a list of drugs that start with z. When the buttons are clicked/data is loaded, I want to replace my viewModel data with what's coming in from the server.

Also, note the console on the jsfiddle page, data looks fine (8 array elements and count=8), but note the console of the viewModel, preferredDrugs and count are different, anyone know why this is?

$(function() {
    $('.load').click(function() {
        var $letter = $(this).attr('value');

        //show spinner
        $('#loading').show();

        //load in drug list data
        $.getJSON('/PreferredDrugList/service/preferredDrugs/' + $letter, function(data) {
            //hide spinner
            $('#loading').hide();

            console.log(data);
            //create observable properties for each of the properties on data
            ko.mapping.fromJS(data, viewModel);
            console.log(viewModel);

        });
    });

});//end ondomready

//default data
var data = {
    preferredDrugs: [],
    count: 0
};

var viewModel = ko.mapping.fromJS(data);

ko.applyBindings(viewModel);
4

1 に答える 1

5

を使用して既存のビューモデルを更新する場合は、次のko.mappingことも試すことができます。

ko.mapping.fromJS(data, {}, viewModel);

..それ以外の..

ko.mapping.fromJS(data, viewModel);

また、jsfiddleページのコンソールに注意してください。データは正常に見えます(8つの配列要素とcount = 8)が、viewModel、preferredDrugs、およびcountのコンソールが異なることに注意してください。これがなぜであるか、誰もが知っていますか?

はい、元の優先薬は通常の配列ですが、新しい優先薬は観察可能な配列です。直接アクセスしようとすると、監視可能な配列は空の配列のように見えます。ただし、オブザーバブルは関数であり、そのように扱う必要があります。

それで...

console.log(myViewModel.preferredDrugs);

...空の配列を返しますが、...

console.log(myViewModel.preferredDrugs());

...実際の配列を返します。

于 2012-08-31T18:12:56.123 に答える