2

我有一项服务可以分块上传许多大文件

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 中执行此操作的最佳做​​法是什么?Observable 属性也感觉不对,怎么观察 2000 个文件的进度?将所有内容放在一个大对象中并在整个应用程序中共享?

4

1 回答 1

3

this回来的原因是undefined当函数被传递时,它的上下文 ( this) 会发生变化。您可以创建一个新函数,使用function.bind. 使用时,function.bind无论您在何处调用新函数或将其分配给什么值/属性,它的上下文都将保持不变。

参见 MDN 了解 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);
    },
  }
})
于 2016-11-22T05:07:25.423 回答