zari
zari

Reputation: 67

Knockout observablearray of observables with arrayMap function

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.

Upvotes: 1

Views: 565

Answers (1)

Hakan Fıstık
Hakan Fıstık

Reputation: 19511

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

Upvotes: 1

Related Questions