jquery-attachdeprecated

Simple jQuery plugin to ensure one-time behavior binding

Usage no npm install needed!

<script type="module">
  import jqueryAttach from 'https://cdn.skypack.dev/jquery-attach';
</script>

README

jQuery Attach/Detach

NPM downloads

jQuery-attach is a simple jQuery plugin to ensure that elements don't get bound to an event multiple times.

Installation

npm install jquery-attach --save-dev

Basic Usage

Attach Behavior — attachBehavior(eventName, cb)

Use this instead of jQuery's on function to initiate the one-time binding.

$('.clicker').attachBehavior('click', function (e) {
  evt.preventDefault();
  // do your thing
});

// or write it in ES6
$('.clicker').attachBehavior('click', e => {
  e.preventDefault();
  // do your thing
});

Arguments:

  • eventName: the event to be handled (e.g. 'click')
  • cb: event's callback function
    • e: return an event object (optional)

--

Detach Behavior — detachBehavior(eventName)

Use this instead of jQuery's off function to detach the element binding.

$('.clicker').detachBehavior('click');

Arguments:

  • eventName: the event to be detached (e.g. 'click')

--

Get Behavior(s) — getBehavior([eventName])

Use this to check what behavior's attached to an element

Sample event binding:

$('.clicker').attachBehavior('click', function(evt) {
  evt.preventDefault();
});

$('.clicker').attachBehavior('custom', function(e) {
  e.preventDefault();
});

Getting the behaviors for the behaviors assigned above

// Get all events (and assigned behavior) attached to this element
console.log( $('.clicker').getBehavior() );

// Get the behavior assigned to this element's "custom" event
console.log( $('.clicker').getBehavior('custom') );

Arguments:

  • eventName: specifies the event in which to get the behavior from (optional)

Additional Usage

Custom Events

jquery-attach can handle Custom Events by using jQuery's trigger function.

See example below:

var $invert = $('.invert');
var $font = $('.font');
var $content = $('.content');

// Attach Custom Events
$content
  .attachBehavior('invertColor', function (e) {
    $content.toggleClass('invert');
  })
  .attachBehavior('toggleFont', function (e) {
    $content.toggleClass('font');
  });

// Trigger "invertColor" Custom Event
$invert.attachBehavior('click', function (e) {
  $content.trigger('invertColor');
});

// Trigger "toggleFont" Custom Event
$font.attachBehavior('click', function (e) {
  $content.trigger('toggleFont');
});

--

Error Handling

There are two errors that can jquery-attach might throw

  • When multiple behaviors have been added to an element's event (e.g. multiple click events for a single button)
  • When the callback argument was passed something that is not a function (e.g. attachBehavior('click', true))

Errors can be handled by using the try...catch statment:

try {
  $('.link').attachBehavior('click', function (e) {
    e.preventDefault();
  });
}
catch (err) {
  console.error(err);
  // handle error here
}

Examples

Tests

Other Notes

  1. jquery-attach supports behavior assignment for elements in the same group or selector (e.g. $('.nav-links'))

  2. jquery-attach supports behavior assignment for different events

    $('.content')
      .attachBehavior('invertColor', function (e) {
        $content.toggleClass('invert');
      })
      .attachBehavior('toggleFont', function (e) {
        $content.toggleClass('font');
      });
    
  3. Using jQuery's on function BEFORE attachBehavior on the same event will also throw an error. (See example below)

    $('.link').on('click', function(){});
    $('.link').attachBehavior('click', function(){});
    
    // the second line above will throw an error
    // saying that the 'click' event
    // already has a behavior attached to it
    
  4. Using jQuery's on function AFTER attachBehavior on the same event will break the intended behavior and will cause the element to be bound to two click events. It's highly suggested to avoid this pattern.

    // DO NOT DO THIS
    $('.link').attachBehavior('click', function(){});
    $('.link').on('click', function(){});
    

Changelog:

1.2.2:

  • Updated error catching and behavior checking to use jQuery's $._data function instead of a custom one.
  • Updated getBehavior to return either a specific event's behavior, or all of the events attached to the selected element
  • Localized jquery.min.js on all the tests and examples /vendor

1.2.1:

  • Fixed detachBehavior to just detach the behavior for the specified event

1.2.0:

  • Added Custom Events binding
  • Added detection of bindings using jQuery "on" function
  • Added examples /examples
  • Added tests /tests
  • Added chaining
  • Added showErrors option
  • Updated source code to ES6 (transpiled to ES5)
  • Updated error handling

1.1.2:

  • Fixed references to the code repository

1.1.1:

  • Published plugin to bower
  • Updated license from MIT to ISC

1.1.0:

  • Enclosed the plugin inside an IIFE
  • Applied mangling on jquery-attach.min.js

1.0.1:

  • Fixed the $ is undefined error by using universal jQuery method

To-Do

  • Add custom events binding
  • Add examples
  • Add test cases
  • Update functionality to account for Other Notes item #4