samedi 28 novembre 2015

emberjs - refactor custom link-to to htmlbars

Previously I had my own custom link-to helper that I blogged about here.

With handlebars I could pass arguments that would cause a re-render if the value changed, for example if I am binding to model that has isLoaded=false, then the LinkView view would re-render when isLoaded=true or the value changed from undefined to its value.

Below is my old handlebars custom link-to helper

Ember.Handlebars.registerHelper('resource-link-to', function(path, options) {
  var args = Array.prototype.slice.call(arguments, 1);
  var resource = this.get(path);
  var resourceRoute = resource.humanize();

  if (!options.fn) {
    options.types = ['STRING', 'STRING', 'ID'];
    options.contexts = [this, this, this];
    args.unshift(path);
    args.unshift(resourceRoute);
    args.unshift(resource.get('displayName'));
  } else {
    options.types = ['STRING', 'ID'];
    options.contexts = [this, this];
    args.unshift(path);
    args.unshift(resourceRoute);
  }
  return Ember.Handlebars.helpers['link-to'].apply(this, args);
});

The ID marker in this line meant it was a binding:

options.types = ['STRING', 'STRING', 'ID'];

I am trying to replicate this in htmlbars in ember 1.13.11 and I have extendted the LinkComponent and overriden willRender like this:

export default LinkComponent.extend({
  willRender() {
    // FIXME: allow for css classes and query params
    Ember.assert('you must specify a resource', this.attrs.resource);

    const resource = this.attrs.resource;

    let resourceRoute = resource.value.humanize();

    if(typeToLinks[resourceRoute]) {
      resourceRoute = typeToLinks[resourceRoute];
    }

    this.set('attrs', {
      params: [resource.value.get('displayName'), resourceRoute, resource],
      view: this.parentView,
      hasBlock: false,
      escaped: true
    });

    this._super(...arguments);
  }
});

I then call it like this:

{{resource-linkto resource=activity.reference}}

The problem is that the resource might be in an isLoading state or partially resolved.

How can I trigger a re-render when the value is resolved?




Aucun commentaire:

Enregistrer un commentaire