area17 / a17-behaviors

JavaScript framework to attach JavaScript events and interactions to DOM Nodes
MIT License
15 stars 5 forks source link

Question on accessing behavior methods from another behavior #3

Closed mattbloomfield closed 2 years ago

mattbloomfield commented 2 years ago

Our menu has a reset method that I need to access from a different behavior.

I've successfully done this with the callMethod method

window.USCC.behaviors.callMethod(
        'usccHeader',
        document.querySelector('header'),
        'reset'
      )()

But it seems to only work intermittently and sometimes I get an error that the method is not defined. What is the recommended approach?

mattbloomfield commented 2 years ago

From what I can tell it only works locally. Maybe this function is not exposed in a non-local env?

13twelve commented 2 years ago

@mattbloomfield I'd send a custom event from one behavior to the other.

So, in one behavior:

document.dispatchEvent(new CustomEvent('foo', {
  detail: {
    bar: 'baz',
  }
}));

And then in the other behavior:

import { createBehavior } from '@area17/a17-behaviors';

const otherBehavior = createBehavior('otherBehavior',
  {
    fooMethod(event) {
      // do thing
      console.log(event.detail.bar); // baz
    }
  },
  {
    init() {
      /* 
      ...
      */
      document.addEventListener('foo', this.fooMethod, false);
    },
    destroy() {
      document.removeEventListener('foo', this.fooMethod);
    }
  }
);

export default otherBehavior;

There is an example in the wiki: https://github.com/area17/a17-behaviors/wiki/More-examples#multiple-instances-of-a-behavior-multiple-behaviors-on-a-single-dom-node-send-messages-between-nodes

You can also send events directly to a node too if you want to be more specific. If you do a search in your app, you'll see a bunch of these events/listeners.

mattbloomfield commented 2 years ago

Ah ok, this makes sense. I will look at the specific ones. Thank you!