meteor-collection-helpers icon indicating copy to clipboard operation
meteor-collection-helpers copied to clipboard

ES6 Getters/Setters support

Open imajus opened this issue 7 years ago • 4 comments

I had to use get/set ES6 syntax in helpers but plugin didn't support those. Here's a patch I suggest to apply in order to support getters/setters in helpers:

_.each(Object.getOwnPropertyDescriptors(helpers), function(descriptor, key) {
  Object.defineProperty(self._helpers.prototype, key, descriptor);
});

The patch is backward compatible with old good helper methods. With that change the following helpers start working:

Orders.helpers({
  // Still works this way
  url() {
    return FlowRouter('order', this);
  },
  // Getters…
  get product() {
    return Products.findOne(this.productId);
  },
  get total() {
    return this.quantity * this.price;
  }
 //TODO: Never actually tested Setters yet
});

imajus avatar May 27 '17 14:05 imajus

Hey @imajus interesting thought, wondering what was the reason that you said you had to use them?

dburles avatar May 29 '17 00:05 dburles

@dburles Using Collection instances in Handlebars E-mail templates on the server. So I need {{order.total}} to work seamlessly. Unlike Spacebars, functions here are called with current template context so this in Collection helpers is not Collection instance. I've found using getters as an elegant way to achieve my goal.

imajus avatar May 29 '17 00:05 imajus

I absolutely agree that this would be very useful, especially for computed properties.

Authors.helpers({
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
});

author.fullName would now work like author.firstName, as it is supposed to be.

And I can confirm that the above fix by @imajus (thanks a lot!) works correctly (using it myself).

medihack avatar Dec 10 '17 13:12 medihack

Seems great! How can i use this?

arvidkastel avatar Dec 03 '19 12:12 arvidkastel