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 個のファイルの進行状況を監視できますか? すべてを 1 つの大きなオブジェクトに入れて、アプリ全体で共有しますか?

4

1 に答える 1

3

this戻ってくる理由はundefined、関数が渡されるとそのコンテキスト ( this) が変化するためです。を使用してコンテキストを明示的に設定した新しい関数を作成できますfunction.bind。新しい関数をfunction.bindどこで呼び出しても、どの値/プロパティに割り当てても、そのコンテキストは同じままです。

Function.prototype.bind については MDN を参照してください

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 に答える