Problems with Knockout observables in a for loop

348 views
Skip to first unread message

whitney...@gmail.com

unread,
Apr 20, 2014, 9:42:03 PM4/20/14
to knock...@googlegroups.com
Howdy!
I'm trying to write a RESTful client for a server that I created a while back and ran into a bit of a snag.  Basically, my client is sending an HTTP request to my server and receiving a JSON in return.  From what I can tell, the networking aspect is in the clear.  I know this because when I call "alert(data.dates.length);" in the self.ajax function but before the for loop,  I get a pop-up box on the page with the correct length.  The problem lies is the self.dates.push() call.  For some reason, this throws off the code and self.dates is not populated correctly.  I have been working at this for hours and cannot get it figured out.
function DatesViewModel(){
var self = this;
self.dates = ko.observableArray();

...
...
  self.ajax(self.datesURI, 'GET').done(function(data) {
for (var i = 0; i < data.dates.length; i++) {
alert(i + "\n" + data.dates[i].date + "\n" + data.dates[i].strAbsent);
self.dates.push({
date: ko.observable(data.dates[i].date),
strAbsent: ko.observable(data.dates[i].strAbsent)
});
}
});
}

ko.applyBindings(new DatesViewModel(), $('#main')[0]);

Patrick Steele

unread,
Apr 21, 2014, 7:21:42 AM4/21/14
to knock...@googlegroups.com
What happens if you add "alert(self.dates().length);" after the for loop completes?  How do you know self.dates isn't populated correctly?  Do you have a binding that isn't updating?

--
You received this message because you are subscribed to the Google Groups "KnockoutJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to knockoutjs+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

sugandhag...@gmail.com

unread,
Apr 24, 2014, 4:47:01 PM4/24/14
to knock...@googlegroups.com, whitney...@gmail.com

I am facing a very similar issue.
My code throws an error right after entering the 'for' loop code when i try to push the elements into an observable. The error that it throws on the console states "Uncaught TypeError: Cannot read property 'push' of undefined "
I am unable to figure out why. i have checked and the web service call is returning proper data. i can set that data into a normal JS array but am unable to do so in an observable array.

Any suggestions?

Patrick Steele

unread,
Apr 25, 2014, 7:36:37 AM4/25/14
to knock...@googlegroups.com
Please show a sample of the JSON data being returned as well as your HTML with the data-bind attributes.  Creating a failing jsFiddle would be a huge help too.

--
Reply all
Reply to author
Forward
0 new messages