Austin Lovell
Austin Lovell

Reputation: 1049

Call a function within same object as a callback

I know my title is a bit confusing but I guess so is the problem.

I am trying to call a function thats on the same object as the caller but within a callback.

serv.factory("repo", function(rest, $location){

return {
    get: function(repoName, cb){
        this.i[repoName].length > 0 ? cb(this.i[repoName]) : rest[repoName].query(cb)   
    },
    i:{
        events: rest.events.query(>>>>>>CALL readyCheck()<<<<<),
        audiences: rest.audiences.query(>>>>>>CALL readyCheck()<<<<<),
        categories: rest.categories.query(>>>>>>CALL readyCheck()<<<<<),
        outcomes: rest.outcomes.query(>>>>>>CALL readyCheck()<<<<<),
        regions: rest.regions.query(>>>>>>CALL readyCheck()<<<<<),
        types: rest.types.query(>>>>>>CALL readyCheck()<<<<<) 
    },
    url:'',
    readyCheck: function(){
        var ready = true
        angular.forEach(this.i, function(value, key){
            if( value.length < 2 ) {
                ready = false
            }
        })
        if(!ready){
            console.log('not ready')
            this.url =  $location.path() !== '/loading' ? $location.path() : this.url
            $location.path('/loading')
        } else {
            console.log('ready')
            $location.path(this.url)
        }
    }
}

})

When I use this.readyCheck, it appears that is has lost it's reference to the parent object (get, i, url, readyCheck)

Any suggestions?

Upvotes: 1

Views: 554

Answers (1)

Enzey
Enzey

Reputation: 5254

The 'this' you are trying to use is inside a different function thus 'this' is different. To be able to access the URL property from within the ready check function store the service into a variable to be able to access it later. Like this:

var service;
service = {
    get: function(repoName, cb){
        this.i[repoName].length > 0 ? cb(this.i[repoName]) : rest[repoName].query(cb)   
    },
    i:{
        events: rest.events.query(>>>>>>CALL readyCheck()<<<<<),
        audiences: rest.audiences.query(>>>>>>CALL readyCheck()<<<<<),
        categories: rest.categories.query(>>>>>>CALL readyCheck()<<<<<),
        outcomes: rest.outcomes.query(>>>>>>CALL readyCheck()<<<<<),
        regions: rest.regions.query(>>>>>>CALL readyCheck()<<<<<),
        types: rest.types.query(>>>>>>CALL readyCheck()<<<<<) 
    },
    url:'',
    readyCheck: function(){
        var ready = true
        angular.forEach(this.i, function(value, key){
            if( value.length < 2 ) {
                ready = false
            }
        })
        if(!ready){
            console.log('not ready')
            service.url =  $location.path() !== '/loading' ? $location.path() : service.url
            $location.path('/loading')
        } else {
            console.log('ready')
            $location.path(this.url)
        }
    }
};

Upvotes: 1

Related Questions