mercredi 30 décembre 2015

How to delay or only set a computed property once a promise has been resolved?

I have an Ember app with a computed model property that I am looking to use in a template. For the purpose of the example, at the moment, I am just logging it in the template to test to the output:

{{log post.content}}

In the model, the computed property "content" calls a getMD ( get markdown ) function:

var Post = DS.Model.extend({
  mdURL: DS.attr('string'),
  content: function() {
    getMD(this.get('mdURL')).then(function(md) {
      // On success
      return md;
    }, function(reason) {
      // On fail
    });
  }.property('content')
});

function getMD(url) {
  return new Promise(function(resolve, reject){
    var xhr = new XMLHttpRequest();

    xhr.open('GET', url);
    xhr.onreadystatechange = handler;
    xhr.responseType = 'text';
    xhr.setRequestHeader('Accept', 'application/text');
    xhr.send();

    function handler() {
      if (this.readyState === this.DONE) {
        if (this.status === 200) {
          resolve(this.response);
        } else {
          reject(new Error('getMD: `' + url + '` failed with status: [' + this.status + ']'));
        }
      }
    };
  });
}

The promise is ultimately returning the data but it is happening too late. The computed property in the template has already come through as undefined.




Aucun commentaire:

Enregistrer un commentaire