简体   繁体   中英

Call method inside function

i have a wizard from a metronic theme where I'm trying to call a function to check if my array contains dublicates.

if I remove this part of my code it works without problems.

console.log(this.checkIfArrayIsUnique()); 

code

var wizard = (<any>$('#m_wizard')).mWizard();        
                    //== Validation before going to next page
                    wizard.on('change', function(wizard) {
                        if(wizard.getStep() > 2){    
                            console.log(this.checkIfArrayIsUnique());                     
                        }
                        mApp.scrollTop();                                        
                    })

Right now my checkIfArrayIsUnique() is just a dummy function

checkIfArrayIsUnique() 
    {
        return true;
    }

how can i call a method outside my 'change' event ? So I'm able to run thru my array and confirm it does not have any dublicates.

the problem is the "function(wizard)" call, since it creates a new scope. But your checkIfArrayIsUnique() ist actually outside of this scope.

Try using ES6 function syntax

wizard.on('change',(wizard) => {
    if(wizard.getStep() > 2){                 
        console.log(this.checkIfArrayIsUnique());                                  
    }
    mApp.scrollTop();                                        
})

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

in your change function the variable this point to current function,to use it,you should make this point to out object,you should write like this:

 var that = this; var wizard = (<any>$('#m_wizard')).mWizard(); //== Validation before going to next page wizard.on('change', function(wizard) { if(wizard.getStep() > 2){ console.log(that.checkIfArrayIsUnique()); } mApp.scrollTop(); }) 

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