Unable to access attribute after fetch - javascript

I am testing some code in my web console (using coffescript)
#user = new Onethingaday.Models.User()
#user.url= "/users/#{current_user.get('nickname')}.json?id_type=nickname"
#user.fetch()
console.log(#user)
console.log(#user.get("facebook_id"))
The console.log(#user) line shows the following:
However, console.log(#user.get("facebook_id")) shows undefined.
I see that user has the facebook_id attribute. How do I retrieve the value of it?

This looks like a timing issue, albeit an odd one. fetch is asynchronous; you need to wait until its success callback is called before trying to access any attributes.
Try this:
#user.fetch success: =>
console.log(#user)
console.log(#user.get("facebook_id"))
It's confusing that the first console.log would show user.attributes.facebook_id existing and the second wouldn't, but console.log is itself asynchronous in Webkit's implementation, so what's going on is that the #user.get call is being resolved immediately (synchronously), whereas the object inspection in the first console.log is resolving later—after the fetch completed.

It looks like facebook_id is a property of the attributes property of the #user object. If that's the case, I'd think the following would work:
#user.attributes.facebook_id

Related

Why is this data showing undefined when there are clearly values?

On my page, I'm logging this:
console.log(self);
console.log(self.data.events);
The self is showing data, however self.data.events is showing undefined, how am I referencing this wrong?
but why is console.log(self.data) working but not console.log(self.data.events)?
As #Nick Parsons hinted in his comment, it might be because console.log behaves asynchronously in some browsers and will not log a "snapshot" at the time it was logged but will reflect updates on whatever is referenced, in this case self.data (which is initially defined as an empty object!)...
I have a feeling that #Dinesh Kumar's comment is on the right track, you're calling these functions after each other:
self.load_event_data();
self.load_zip_codes();
self.bind_events();
self.handle_filter_params();
self.cluster();
the issue is within self.cluster() but it is possible that the AJAX call you're making in self.load_event_data() is not be done yet when self.cluster() is called, so I'd suggest you try and call self.cluster() from within self.load_event_data() whenever you got data updated with the events.

React: Delay rendering of JSON data?

I have the following React class. At first, the console will print an empty array {}, which will return the empty div. However, half a second later the console will print the correct values - but the empty div remains. How should I change the class to properly load the JSON?
var TableData = React.createClass({
render: function() {
console.info(JSON.stringify(this.props.summary));
if (!this.props.data || !this.props.summary) {
return <div>Loading name table..</div>
}
var summary = this.props.table;
var nameTable = summary.nameTable;
var nameTableArr = Object.values(nameTable);
return ( // A table is returned here, works with the same data structure as is present in the JSON
If I go to the console, the console.info prints an empty JSON string {} initially, which correctly returns the "loading names table..." div. However, data is printed in the console half a second later, but it never proceeds to go out of the if statement and populate the table.
It works if I change the nameTable var to include "manual" data, so it must be something with rendering the server-side data that's delayed half a second.
How could I change the above class to delay rendering for, say, 1 second and then populate the table? It would work in that case I suspect.
Removing the if statement results in Uncaught TypeError: Cannot convert undefined or null to object in the console, which makes sense since the string is indeed empty for half a second.
Im not a React experienced, but this looks like you have problem with asynchronous behavior.
In order to help you more, Ill need the part of the code where ajax is called.
The whole issue in my opinion is that your code is triggered first when there are no results yet, and after data are loaded it will not trigger again.
So take a closer look at your handling of AJAX async stuff, cause your issue is there.

Firebug's console.log: debugging asynchronous variables

I am trying to debug some javascript code. The variable I want to debug is a JS object of objects, loaded asynchronously (ajax callback). I am debugging it outside the callback.
I am pretty sure that the problem is a race-condition problem, but I want to be sure (and it is not my question).
The problem I find when debugging is that console.log gives me an information which does not make sense with what the code is doing. Therefore, either I am missing something in the code, or the result I see in the console is the not a snapshot of the state of the variable when I runned console.log.
If it turns out to be the later, how can i get a snapshot of the state of an asynchronously loaded JS object?
This is a simplified example of the code:
//This call takes a while to invoke the callback
$.get("url",function(data){
//Process data
globalVariable = data; //JSON (Object of objects)
}
//Couple lines afterwards
/* This console.log shows (in Firebug's console) "Object { }" and when I click it,
I can see the object with all its fields filled (oher objects)
*/
console.log(globalVariable);
for(var e in globalVariable){
//Does not enter here, meaning that the object is empty
}
console.log is itself asynchronous and it shows references rather than snapshots, sometimes.
If you log an object you will get a nice clickable interface where you can inspect the object. If the object changes you will see those changes reflected there.
If you want a real snapshot you're going to have to do some serialization and serializing objects is not trivial. If your objects just are data and have no functions or references you can use JSON.stringify(obj, undefined "\t").
A smarter way is to pause your asynchronous events so you can inspect the latest state of the object.
Write it like this instead. This way globalVariable will have the data before you act upon it.
$.get("url",function(data){
//Process data
globalVariable = data; //JSON (Object of objects)
for(var e in globalVariable){
//this will run
}
}

Different behavior seen accessing value in stored variable vs function call that returns the variable

Apologies for what must be a total newbie question. I'm starting to play with Backbone talking to an existing Rails app. I'm using the Console in Chrome to test out some JS functions, and I'm seeing behavior that I cannot understand.
I've defined a JS function called apiGet which just wraps a jQuery AJAX call with some custom stuff jammed into the HTTP request header.
When I call apiGet and store the result in a variable, I can then call .responseText on that variable and see the contents of that field.
However, if I just try to call .responseText on the apiGet(...) call, i.e. apiGet(...).responseText the result displayed is undefined. This makes no sense to me :-)
I'm missing something obvious -- can someone clue me in?
Here's what the console looks like:
> var url = 'http://localhost:3002/api/exercises/11';
undefined
> result = apiGet(url);
Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
> result.responseText
"{"id":1,"number":2,"version":1,"markup":null,"html":null,"background":null}"
> apiGet(url).responseText
undefined
It looks like your function apiGet returns an xhr (request object). This will execute asynchronously, so that responseText isn't available until the response comes back from the server. When you call the property directly on the return, it happens so fast that the server hasn't responded yet, but when you use the console manually, by the time you type out result.responseText and press enter, the result is already in.
Just a guess of course, since I haven't seen the contents of getApi.

Reading data from multiple $.get() using $.when()

I'm using jQuery's $.when() to handle multiple $.get() requests. This is how I have it set up.
var request1 = $.get('myURL');
var request2 = $.get('mySecondURL');
$.when(request1, request2).done(go);
function go(request1, request2){
console.log(request1);
console.log(request2);
}
Everything works great. Chrome's console shows
[#document, "success", Object]
I know that #document is what I need to read, but what is the syntax to get it? Every example I've seen uses anonymous functions, which I'm not use to and bug me, coming from OOP AS3.
I've tried console.log(request1[0]); which works, but there has to be a more proper way. Something like request1.data or $(request1).$('#document');
Like I said, I'm a heavy Flex developer coming into JS and jQuery so the syntax I'm still trying to pickup.
According to the documentation for $.when, request1[2] has the jqXHR object, which in turn has responseText member. If you use console.log in Chrome at least, you can see the contents of the jqXHR to find what member you specifically want to access, but it's probably responseText.
Create a jQuery object and use it like you would use one created from a selector: $(request1)
For example, $(request1).appendTo('#out') would append the newly loaded content to an element with id="out".

Categories

Resources