Pattern for sending events from parent to child component in Blaze

276 Views Asked by At

Let's assume we have the following abstract setup:

<template name="parent">
  {{> child childProps}}
</template>

and a helper function:

Template.parent.helpers({
  childProps() {
    const instance = Template.instance();
    return {
      // whatever props we want
    };
  }
});

I am wondering what's the best way to allow parent component to send events to it's child component.

There are at least two methods I can think of:

  1. Don't send events and only control the child through props. This is probably what some people would recommend doing. The problem is that this approach requires child to track it's Template.currentData() context and react accordingly to potential changes, which makes the implementation much more complicated and error prone.

  2. Create instance.emitter = new EventEmitter() in the onCreated hook and pass it to the child data context, so that it can add listeners for certain events. This seems more flexible and less error prone, but still a little complicated as the child needs to properly manage listeners cleanup not only in it's lifecycle methods, e.g. onDestroy but also as a result to current data context changes.

Does anyone have other ideas how this pattern could be implemented in Blaze? Is there some kind of standard way of doing it, or maybe some packages that already solve this problem?

0

There are 0 best solutions below