peerlibrary / meteor-blaze-components

Reusable components for Blaze
http://components.meteorapp.com/
BSD 3-Clause "New" or "Revised" License
354 stars 26 forks source link

Syntactic sugar using Object.defineProperty #90

Closed mcbain closed 9 years ago

mcbain commented 9 years ago

To get rid of the the ReactiveVars .get() and .set calls one you use Object.defineProperty() to define the fields as getter/setter on the component instance.

// maybe add this method to BlazeComponent class
addField(name) {
  this.state = this.state || new ReactiveDict();
  Object.defineProperty(this, name, {
        get: () => this.state.get(name),
        set: (value) => this.state.set(name, value)
      });
}
onCreated() {
 this.addField('counter');

 // sets value reactively
 this.counter = 4711;
}

onClick(event) {
    this.counter = this.counter + 1;
}

customHelper() {
    if (this.counter > 10) {
      return "Too many times";
    }
    else if (this.counter === 10) {
      return "Just enough";
    }
    else {
      return "Click more";
    }
  }
mitar commented 9 years ago

True. We were looking into this, but then decided to go with a more conservative way of using reactive-field package. Less lines of code to use. No need to create both the reactive var, and getters and setters.

The example in the README already uses reactive-field. So not sure why you are bringing this up again?

BTW, I think that in ES2015 you have an easier way to define getters and setters, you do not have to call Object.defineProperty.

Also, look into computer-field which is a good way to wrap a reactive source into an transformation and then expose a result as a field.

mitar commented 9 years ago

Do you know if there is a good ES2015 syntax for:

class FooComponent extends BlazeComponent
  @register 'FooComponent'
mcbain commented 9 years ago

@mitar sorry, my knowledge about coffescript is very limited

rclai commented 9 years ago

I think it might be decorators, but that's no supported in Meteor's ES2015 config.

mitar commented 9 years ago

Example?

rclai commented 9 years ago
@register('ListComponent')
class ListComponent extends BlazeComponent {}

However, it might be way too generic of a decorator name.

mitar commented 9 years ago

There are decorators?

rclai commented 9 years ago

Yeah, but they're ES2016 and not available in Meteor's ES2015, see this discussion.