2016-11-22 35 views
1

我有一个服务上传许多大型文件块灰烬通回调服务 - 未定义,则此

export default Ember.Service.extend({ 
    run(files, callbacks) { 
    // ugly async FileReader and ajax 
    // calling callbacks during the process 
    } 
}) 

我需要一大堆的回调出现进展,但问题是这些回调之内this未定义

export default Ember.Component.extend({ 
    upload: Ember.inject.service(), 

    didInsertElement() { 
    // bind fileinput change event to set up pending files 
    }, 

    ondonesingle(self, file, uuid) { 
    // this is undefined 
    // self is real this 
    }, 

    actions: { 
    submit() { 
     let callbacks = { 
     ondoneall: this.ondoneall, 
     ondonesingle: this.ondonesingle, 
     onprogressall: this.onprogressall, 
     onprogresssingle: this.onprogresssingle, 
     onerror: this.onerror, 
     object: this // will be passed as first argument to each callback 
     }; 
     this.get('upload').run(this.get('pending_files'), callbacks); 
    }, 
    } 
}) 

要解决这个问题,我必须随身携带这个参考。

它的工作原理,但它感觉非常错误。 Ember的最佳做法是什么?可观察财产也感觉错误,我将如何观察2000年文件的进展?把所有东西放在一个大对象中,并在应用程序中分享它?

回答

1

原因this正在回来undefined是当函数传递它的上下文时(this)的变化。您可以使用function.bind创建一个具有明确设置上下文的新功能。当使用function.bind时,无论您在哪里调用新函数或您分配了哪个值/属性,它的上下文都将保持不变。

see MDN for Function.prototype.bind

export default Ember.Component.extend({ 
    upload: Ember.inject.service(), 

    didInsertElement() { 
    // bind fileinput change event to set up pending files 
    }, 

    ondonesingle(file, uuid) { 
    }, 

    actions: { 
    submit() { 
     let callbacks = { 
     ondoneall: this.ondoneall.bind(this), 
     ondonesingle: this.ondonesingle.bind(this), 
     onprogressall: this.onprogressall.bind(this), 
     onprogresssingle: this.onprogresssingle.bind(this), 
     onerror: this.onerror.bind(this) 
     }; 
     this.get('upload').run(this.get('pending_files'), callbacks); 
    }, 
    } 
})