dburles / meteor-collection-helpers

⚙️ Meteor package that allows you to define helpers on your collections
https://atmospherejs.com/dburles/collection-helpers
MIT License
498 stars 31 forks source link

ES6 Getters/Setters support #79

Open imajus opened 7 years ago

imajus commented 7 years ago

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
});
dburles commented 7 years ago

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

imajus commented 7 years ago

@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.

medihack commented 6 years ago

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).

arvidkastel commented 4 years ago

Seems great! How can i use this?