Bind Callback Or JS Class To DOM Elements – Necktie

Category: Javascript , Recommended | March 20, 2021
Author:leshniak
Views Total:63 views
Official Page:Go to website
Last Update:March 20, 2021
License:MIT

Preview:

Bind Callback Or JS Class To DOM Elements – Necktie

Description:

Necktie is a DOM binding JavaScript library that allows you to bind a callback function or JavaScript Class to DOM elements.

Powered by the MutationObserver API to watch for changes being made to the DOM tree, which means the plugin works on any element even if it’s created or removed dynamically.

How to use it:

1. Install and import the Necktie.

# Yarn
$ yarn add @lesniewski.pro/necktie
# NPM
$ npm i @lesniewski.pro/necktie
import { Necktie } from '@lesniewski.pro/necktie';

2. Or directly import the Necktie JavaScript library into the document.

<script src="dist/necktie.umd.js"></script>

3. Initialize the Necktie and start listening for DOM changes.

const tie = new Necktie();
tie.startListening();

4. Bind a callback function to DOM elements

tie.bind('.element', (element) => {
  console.log(element);
  return (removedElement) => {
    console.log(removedElement);
  };
});

5. Bind a class to DOM elements.

class myClass {
  constructor(element) {
    console.log("Binded to:", element);
    this._element = element;
    window.addEventListener("custom:addListItemClicked", this.createItem);
  }
  createItem = () => {
    const newItem = document.createElement("li");
    newItem.innerText = `Item no. ${this._element.childElementCount + 1}`;
    this._element.appendChild(newItem);
  };
  destroy() {
    window.removeEventListener("custom:addListItemClicked", this.createItem);
  }
}
tie.bindClass(".element", myClass);

6. Watch for attributes changes with the observeAttributes function.

tie.observeAttributes(true/false);

You Might Be Interested In:


Leave a Reply