vendredi 22 janvier 2016

The way to bind this for later invocation in Ember

Just wondering how to handle "later invocation" when need to reference "this" in the outer scope. Aliase seems not good practice based on idomatic.js. And I quote:

Beyond the generally well known use cases of call and apply , always prefer .bind( this ) or a functional equivalent, for creating BoundFunction definitions for later invocation. Only resort to aliasing when no preferable option is available.

So is there any opinionated way in Ember? For example:

export default Ember.Route.extend({
  model() {
    return new Ember.RSVP.Promise(function(resolve) {
      Ember.run.later(function() {
        resolve({ msg: 'Hold Your Horses' });
      }, 3000);
    });
  },

  setupController(controller, model) {
    console.log(model.msg); // "Hold Your Horses"
  }
});

If, in the Ember.run.later() I want to do something after resolving with this:

this.controllerFor("application").set("dataReady", true);

for example.

I suppose, using aliase that would be:

  model() {
    let that = this;
    return new Ember.RSVP.Promise(function(resolve) {
      Ember.run.later(function() {
        that.controllerFor('application').set('dataReady', true);
        resolve({ msg: 'Hold Your Horses' });
      }, 3000);
    });
  },

But what's the better way?




Aucun commentaire:

Enregistrer un commentaire