...

View Full Version : Resolved Undefined variable in function - scope issue?



nzbluefish
10-27-2009, 08:35 AM
Hi all,

I'm just starting out with Javascript as a development language and this will probably be a relatively simple problem for someone to solve for me.

I am trying to access a variable (this.bodyEl.innerHTML) from within a function but get an error message indicating that it is "undefined". I know that it is a valid variable because I call it elsewhere outside of the inner function itself.

I'm sure this is just a scope issue, but I'd welcome any suggestions on how to solve it with an explanation of where I've gone wrong if you have the time.

Here's the code:



displayFeed: function(responseData) {
this.bodyEl.innerHTML = "xxxx"; // I can see this
var responseDoc = Presto.Util.parseXml(responseData);
var items = Ext.DomQuery.select("/rss/channel/item", responseDoc);
items.each(function(item, bodyHTML) {
var rssTitle = Ext.DomQuery.selectValue("/title", item);
var rssDescription = Ext.DomQuery.selectValue("/description", item);
var rssLink = Ext.DomQuery.selectValue("/link", item);
// but this results in an undefined error
this.bodyEl.innerHTML = '<a href="' + rssLink + '">' + rssTitle + '</a><br/>';
}); // end of items processing
}


This is a fragment of the code from my script. The first access of "this.bodyEl.innerHTML" works fine, but the second access in the items.each loop doesn't and I get an undefined variable error.

Is this a scoping problem, and if so how is it best solved.

Thanks in advance, Innes (NZ)

A1ien51
10-27-2009, 04:09 PM
This inside the each is referring to something else. You can see that by inspecting this in firebug with a breakpoint.

You need to make a reference to this outside of the each loop.


var that = this;
items.each(function(item, bodyHTML) {
...
that.bodyEl.innerHTML = '<a href="' + rssLink + '">' + rssTitle + '</a><br/>';


Eric

nzbluefish
10-28-2009, 10:12 AM
Hi Eric,

Thanks for the reply and the coding tip. It worked perfectly and I could access the outer object.

I had another tip passed on to me that also worked for this so, I'll post that as well:



...
items.each(function(item) {
var rssTitle = Ext.DomQuery.selectValue("/title", item);
var rssDescription = Ext.DomQuery.selectValue("/description", item);
var rssLink = Ext.DomQuery.selectValue("/link", item);
// but this results in an undefined error
this.bodyEl.innerHTML = '<a href="' + rssLink + '">' + rssTitle + '</a><br/>';
}, this); // end of items processing
...


Cheers, Innes (NZ)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum