【问题标题】:Call a function within same object as a callback在同一对象中调用函数作为回调
【发布时间】:2014-11-21 18:26:07
【问题描述】:

我知道我的标题有点混乱,但我想问题也是如此。

我正在尝试调用与调用者在同一个对象上但在回调中的函数。

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)
        }
    }
}

})

当我使用 this.readyCheck 时,它似乎丢失了对父对象的引用(get、i、url、readyCheck)

有什么建议吗?

【问题讨论】:

标签: angularjs object callback


【解决方案1】:

您尝试使用的“this”位于不同的函数中,因此“this”不同。 为了能够从就绪检查函数中访问 URL 属性,请将服务存储到一个变量中,以便以后能够访问它。像这样:

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)
        }
    }
};

【讨论】:

    猜你喜欢
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多