Finding and removing a DOM Element kept within a closure on a jQuery plugin instance

156 Views Asked by At

In short, I have a jQuery plugin that holds an array of closures, each of these closures contain an array that hold references to DOM elements the plugin is currently responsible for. As of right now, I am trying to find a way to locate and delete references to a specified element or group of elements from these closures. Removing them from the array does not sem entirely difficult as jQuery and JavaScript both offer methods to achieve that. However, I am having difficulty locating the elements in the arrays themselves. Here is what I have:

function _generate_closures (default_color, inst) {
  var color  = default_color;
  return {
    update : function (style) {
      color = style || default_color;
    },
    apply : function (style) {
      style = style || color;
      for (var i = 0; i < group.length; i++)
        group[i].css('color', style);
    },
    add : function ($elem) {
      group.push($elem);
    },
    remove : function ($elem)  {
      // Search for and delete elements from 'group' array
    },
    unbind_events : function (selector) {
      // unbind using namespaced events
    }
  };
}

I understand I can use a returned function to do the searching, but it's the actual searching I just can't seem to crack. I may also be approaching this from the complete wrong angle which I feel is more likely the case.

I have tried comparing the current element to every element in the closure, using jQuery's $.inArray(element, group) still finding nothing. I even used group.indexOf(element) and still have not been able to programmatically decide of an element is the same as the one specified by a user.

1

There are 1 best solutions below

1
On BEST ANSWER

JQuery provides an .is function (https://api.jquery.com/is/) to test if an element is the same.

function _generate_closures (default_color, inst) {
  var group = [];
  var color = default_color;
  return {
    update : function (style) {
      color = (style) ? style : default_color;
    },
    apply : function (style) {
      style = (style) ? style : color;
      for (var i = 0; i < group.length; i++) {
        group[i].css('color', style);
      }
    },
    add : function ($elem) {
      group.push($elem);
      alert('Group length is ' + group.length);
    },
    remove : function ($elem)  {
      for (var i = 0; i < group.length; i++) {
        if (group[i].is($elem)) {
         group.splice(i,1);
        }
        alert('Group length is ' + group.length);
      }
    },
    unbind_events : function (selector) {
      // unbind using namespaced events
    }
  };
}

var obj = _generate_closures('orange');
var $el= $('li:nth-child(2)');
obj.add($el);
obj.apply();
obj.remove($el);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>line 1</li>
  <li>line 2</li>
  <li>line 3</li>
  <li>line 4</li>
</ul>