Knockout observablearray of observables with array

2019-07-25 03:59发布

I have a problem creating observable array of observables. I search on google but didn't find a solution. It may be something simple that I can't notice, because I'm new to Knockout. But I have the model:

eventsModel = function () {
   var self = this;

   self.endTimeInMinutes = ko.observable();
   self.events = ko.observableArray([]);
   self.startTripTime = ko.observable();
   self.endTripTime = ko.observable();
}

and I want to have an observables items in my array so I write a ViewModel and bind the model.

eventItemViewModel = function(o) {
    var self = this;

    self.BeginInMinutes = ko.observable(o.BeginInMinutes);
    self.Type = ko.observable(o.Type);
};

var events = new eventsModel();
ko.applyBindings(events);

And I'm fetching the data using AJAX:

function GetEvents() {
    $.ajax({
        url: "Contact.aspx/GetEvents",
        async: true,
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            var temp = data.d;
            endTimeInMinutes = temp["EndInMinutes"];
            eventsArr = temp["Events"];
            eventsArray = JSON.parse(JSON.stringify(eventsArr));
            events.events(eventsArray);
        },
    });
}

After this I have an observable array but without observables values inside. Now I trying to add in my AJAX method:

events.events(ko.utils.arrayMap(eventsArray, function(eve) {return new eventItemViewModel(eve); }));

But if I do console.log on this, then I am getting array of objects, and in each object there is a BeginInMinutes and Type, but it's value is like function d()... etc.

I'm really get stucked with it, and I believe I made some very simple mistake somewhere.

Thanks for helping me.

1条回答
闹够了就滚
2楼-- · 2019-07-25 04:41

You already got an observableArray with observable element inside it,
Your problem really is with getting those values
use this code to get the real value of the first element in the array.

console.log(events.events()[0].BeginInMinutes());
查看更多
登录 后发表回答