简体   繁体   中英

call function with parameters of two different functions

I have two different functions which gets parameters:

push.on('registration', function(data) {
        var id = data.registrationId;
        });


push.on('notification', function (data) {
        var count = data.count;
        });

Now I want to use the variables id and count in another new function:

function three(id, count){

var _id = id;
var _count = count;

}

How is that possible?

var id, count;

push.on('registration', function(data) {
    id = data.registrationId;
});


push.on('notification', function (data) {
    count = data.count;
});

Now you can invoke three(id, count) . The issue is that you'll have to wait until both values are present before calling three . Probably you're looking for something along these lines:

var id, count;

push.on('registration', function(data) {
    id = data.registrationId;
    callThree();
});


push.on('notification', function (data) {
    count = data.count;
    callThree()
});

function callThree() {
    if (id && count) {
        three(id, count);
    }
}
push.on('registration', function(data) {
    var id = data.registrationId;
    push.on('notification', function (data) {
        var count = data.count;
        three(id,count)
    });

 });

UPDATE BASED ON COMMENT : Assuming the order of event,

If you aren't sure what order the events will occur, you may need to get id and count outside their function scopes and then, when one push function fires, check to see if the other has, and if so, call your three(id, count) . One way, is to just declare the variables outside their functions, and then update their value accordingly.

var id = null;
var count = null;

push.on('registration', function(data) {
        id = data.registrationId;
        count !== null ? three(id, count) : null
        });


push.on('notification', function (data) {
        count = data.count;
        id !== null ? three(id, count) : null
        });

The reason why you can't use 'id' and 'count' variables in function three() is because they are declared within the scope of the individual functions. To use them in function three() simply move it to a higher scope.

Here's how I would approach your problem:

var id, count;

function one() {
    push.on('registration', function(data) {
         id = data.registrationId;
    });
}

function two() {
    push.on('notification', function (data) {
        count = data.count;
    });
}

function three(){
    var _id = id;
    var _count = count;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM