Reputation: 11767
I have the following code which registers my iOS device with my APNS server:
pushNotification.registerDevice({
alert: true,
badge: true,
sound: true,
pw_appid: "***",
appname: "***"
},
function (status) {
var deviceToken = status['deviceToken'];
},
function (status) {
console.warn('failed to register : ' + JSON.stringify(status));
navigator.notification.alert(JSON.stringify(['failed to register ', status]));
});
This runs onLoad
, but I need to access deviceToken
outside of the scope of pushNotification.registerDevice() function (status)
.
Is it possible, in this case, to access deviceToken
which is inside a function within a function, outside of the function?
I thought I could make it a global variable, by using window.deviceToken
, then calling that later on, but it returns undefined.
Upvotes: 1
Views: 157
Reputation: 18850
If you're assigning the token to a global and finding its undefined when you try to use it, you will probably find its because the registerDevice ajax hasn't yet received a response.
Try separating your callback into a separate function, and launch any dependant functions from there.
function registerSuccess(status) {
// Store token globally
token = status["deviceToken"];
// or pass as an argument
// call functions that depend on the token
Foo(token);
Bar(); // uses global
}
Personally I would try and pass as an argument, save polluting the global namespace.
Upvotes: 2
Reputation: 298096
You could give deviceToken
a broader scope:
var deviceToken;
pushNotification.registerDevice({
alert: true,
badge: true,
sound: true,
pw_appid: "***",
appname: "***"
},
function(status) {
deviceToken = status['deviceToken'];
},
function(status) {
console.warn('failed to register : ' + JSON.stringify(status));
navigator.notification.alert(JSON.stringify(['failed to register ', status]));
});
Upvotes: 3
Reputation: 707158
Change it to make deviceToken
a global variable so it is available in outside scopes by referencing the global scope directly.
function (status) {
window.deviceToken = status['deviceToken'];
},
If you just want it in a parent scope, not necessarily at the global scope, you can define it in the desired parent scope and then NOT redeclare it in your function:
var deviceToken;
pushNotification.registerDevice({
alert: true,
badge: true,
sound: true,
pw_appid: "***",
appname: "***"
},
function (status) {
deviceToken = status['deviceToken'];
},
function (status) {
console.warn('failed to register : ' + JSON.stringify(status));
navigator.notification.alert(JSON.stringify(['failed to register ', status]));
});
Upvotes: 2