Reputation: 1
The code below attempts to open a new tab for the corresponding post object, when its image is clicked in popup.html. For some reason, the new tab is blank and isn't going to the right page as specified by this.Link in the Post singleton. Any help would be appreciated!
<html>
<head>
<style>
body {
min-width:357px;
overflow-x:hidden;
}
img {
margin:5px;
border:2px solid black;
vertical-align:middle;
width:75px;
height:75px;
}
</style>
<script>
var req = new XMLHttpRequest();
req.open(
"GET",
"http://thekollection.com/feed/",
true);
req.onload = showPosts;
req.send(null);
function showPosts() {
var elements = req.responseXML.getElementsByTagName("item");
for (var i = 0, item; item = elements[i]; i++) {
var description = item.getElementsByTagName("description")[0].childNodes[0].nodeValue;
var link = item.getElementsByTagName("link")[0].childNodes[0].nodeValue;
var txtLink = link.toString();
var txtDesc = description.toString();
var start = txtDesc.indexOf("\"") + 1;
var end = txtDesc.indexOf(".jpg") + 4;
var imgURL = txtDesc.substring(start, end);
var post = new function(){
this.Link = txtLink;
this.Description = txtDesc;
this.ImageURL = imgURL;
this.imgElement = document.createElement("image");
this.displayTab = function(){
chrome.tabs.create({'url' : this.Link}, function(tab){});
}
}
post.imgElement.addEventListener("click", post.displayTab, false)
post.imgElement.src = post.ImageURL;
document.body.appendChild(post.imgElement);
}
}
</script>
</head>
<body>
</body>
Upvotes: 0
Views: 240
Reputation: 57651
You register post.displayTab
as an event listener on post.imgElement
which means that the value of this
will be post.imgElement
when the event listener is called. Consequently, there is no Link
property (this.Link
is undefined). One way to avoid this problem would be registering the event handler differently:
post.imgElement.addEventListener("click", function() {
post.displayTab();
}, false)
post.displayTab
is called as a method of the post
object here so this
variable will be set correctly. The other option is to stop using this
in post.displayTab
:
this.imgElement = document.createElement("image");
var me = this;
this.displayTab = function(){
chrome.tabs.create({'url' : me.Link}, function(tab){});
}
The me
variable remembers the "correct" this
value.
Upvotes: 1