kakoma
kakoma

Reputation: 1203

Javascript variable scope with event handler

This is the nth question about JS variable scope but I read through the rest and didn't quite get an answer.

var notification = window.webkitNotifications.createNotification(
'image.png',                      // The image.
'New Post: ',// The title.
'New stuff'// The body.
);

var itemLink = 'http://pathtothefile.com';

notification.onclick = function(itemLink) { 
window.focus(); 
window.open(itemLink,'_blank' );
this.cancel(); 
};

notification.show();

How do i get itemLink, which is defined in the global scope, to work in the onclick function?

Upvotes: 0

Views: 309

Answers (2)

Joseph
Joseph

Reputation: 119847

During name conflicts, local variables take precedence. Remove or rename the argument itemLink.

notification.onclick = function(something_else) { 
    //global itemLink should be accessible
};

Upvotes: 1

gdoron
gdoron

Reputation: 150253

Remove the parameter from the function:

notification.onclick = function(itemLink) { // overrides itemLink in the global
                                            // object.

Fixed code:

notification.onclick = function() { 
    window.focus(); 
    window.open(itemLink,'_blank' );
    this.cancel(); 
};

Upvotes: 2

Related Questions