fortm fortm - 1 year ago 91
jQuery Question

Unbind to multiple namespaced events in jquery

is it possible to unbind using jquery to multiple namespaced custom events at once ?

Ex : Custom Events -


I tried -


It gives stack limit exceeded error however


Below seems to work but is there more strict event naming possible so that it only affects those resize events which have names as above containing table ?


Answer Source

To remove only the resize events with specified namespaces you can do:

$(window).off("resize.table-100 resize.table-101 resize.table-300");

.off( events [, selector ] [, handler ] ):

events Type: String One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin".


In the snippet I extended jQuery with a function so that you may write something like:

$(window).OffRegexNameSpaces("resize", /^table-\d{3}/);

In order to remove from the window element all resize events having a namespace starting with "table-" and ending with 3 digit. This in order to avoid to write:

$(window).off("resize.table-100 resize.table-101 resize.table-300");


// OffRegexNameSpaces:
// parameters: event --> single event
// regexNamespace --> a regex pattern for namespaces
$.fn.OffRegexNameSpaces = function (event, regexNamespace) {
  if (typeof event !== 'string' && namespaces instanceof RegExp) {
    return this;
  return this.each(function (index, element) {
    var elemData = $._data(this);
    var resultNamespaces = $.map([event], function (eventObj, index) {
      if (regexNamespace.test(eventObj.namespace)) {
        return event + '.' + eventObj.namespace;
    if (resultNamespaces.length > 0) {
      $(this).off(resultNamespaces.join(' '));

$(window).on('resize resize.table-100 resize.table-101 resize.table-300', function(e) {
  alert(e.type + ((e.namespace === undefined || e.namespace.length == 0) ? '' : '.' + e.namespace));

$(function () {
  $('#btn1').on('click', function(e) {
  $('#btn2').on('click', function(e) {
  $('#btn3').on('click', function(e) {
  $('#btn4').on('click', function(e) {

  $('#btnUnbind').on('click', function(e) {
    $(window).off("resize.table-100 resize.table-101 resize.table-300");

  $('#btnUnbindAll').on('click', function(e) {
    $(window).OffRegexNameSpaces("resize", /^table-\d{3}/);
<script src=""></script>

<button id="btnUnbind">UnBind all resize events with namespaces</button>
<button id="btnUnbindAll">UnBind all resize events</button>
<button id="btn1">Trigger resize.table-100</button>
<button id="btn2">Trigger resize.table-101</button>
<button id="btn3">Trigger resize.table-300</button>
<button id="btn4">Trigger resize</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download