Skip to content

Adding more behaviors

Mike Byrne edited this page Dec 24, 2021 · 1 revision

If you've exposed manageBehaviors in your application JavaScript set up:

import { manageBehaviors } from '@area17/a17-behaviors';
import * as Behaviors from './behaviors';

window.A17 = window.A17 || {};
window.A17.breakpoints = ['xs', 'sm', 'md', 'lg', 'xl', 'xxl'];

document.addEventListener('DOMContentLoaded', () => {
    window.A17.behaviors = manageBehaviors;
    window.A17.behaviors.init(Behaviors);
});

Adding single behaviors via script tags

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

if (window.A17 && window.A17.behaviors && typeof window.A17.behaviors.add === 'function') {
    window.A17.behaviors.add(createBehavior('singularAdded',
        {
          setBar(val) {
            this.bar = val;
          },
          alert() {
            window.alert('foo');
          }
        },
        {
          init() {
            this.foo = 'bar';
            this.setBar('baz');
          },
          destroy() {
          }
        }
    ));
}

And then, include via HTML:

<script src="/newBehavior.js" async="true"></script>

Or, dynamically via JavaScript:

let behaviorScript = document.createElement('script');
behaviorScript.async = true;
behaviorScript.src = '/newBehavior.js';
document.body.appendChild(behaviorScript);

Adding multiple behaviors via script tags

export { default as newBehavior } from './behaviors/newBehavior';
export { default as anotherNewBehavior } from './behaviors/anotherNewBehavior';

if (window.A17 && window.A17.behaviors && typeof window.A17.behaviors.add === 'function') {
  window.A17.behaviors.add(Behaviors);
}

And then, include via HTML:

<script src="/newBehaviors.js" async="true"></script>

Or, dynamically via JavaScript:

let behaviorsScript = document.createElement('script');
behaviorsScript.async = true;
behaviorsScript.src = '/newBehaviors.js';
document.body.appendChild(behaviorsScript);

Adding behaviors inline via script tags

<script>
document.addEventListener('DOMContentLoaded', () => {
  if (window.A17 && window.A17.behaviors && typeof window.A17.behaviors.add === 'function') {
    window.A17.behaviors.add(
      'inline',
      {
        setBar(val) {
          this.bar = val;
        },
        alert() {
          window.alert('foo');
        }
      },
      {
        init() {
          this.foo = 'bar';
          this.setBar('baz');
        },
        destroy() {
        }
      }
    );
  }
});
</script>