freefaller freefaller - 3 months ago 19
jQuery Question

Create collection of objects, then add handler to all objects

In jQuery, is there a way to create an array of objects which it's then possible to add a handler to them all?

For example, I have a function that returns a jQuery object, and I want to call that function multiple times. Each time the function returns an object and I want to add that object to the array. Once all the objects are added, I want to add a handler to them all...

The following is a vast simplification of the desired result... the actual handler is much more complex, therefore I don't want to specifically add it each time

// I KNOW THIS DOESN'T WORK...
var allObj = [];
allObj.push(myFnc("#txt1"));
allObj.push(myFnc("#txt2"));
allObj.push(myFnc("#txt3"));
allObj.on("change", function() { alert("hello world"); });

// I also tried, this also failed
$(allObj).on("change", function() { alert("hello world"); });


I'm specifically interested to know if it's possible to create the object collection.

I'm aware that one solution to the above is as follows, but that is not my question...

function handlerFnc() { alert("hello world"); }
myFnc("#txt1").on("change", handlerFnc);
myFnc("#txt2").on("change", handlerFnc);
myFnc("#txt3").on("change", handlerFnc);

Answer

You can use add()

Create a new jQuery object with elements added to the set of matched elements.

var myFnc = function(inputId) {
  var id = inputId.replace('#', '');
  var div = $('<div >', {
    id: inputId.replace('#', ''),
    text: inputId
  })
  div.appendTo(document.body)
  return div;
}

var allObj = myFnc("#txt1"); //Create initial object using first function call
allObj = allObj.add(myFnc("#txt2"));
allObj = allObj.add(myFnc("#txt3"));
allObj.on("click", function() {
  alert("hello world: " + this.textContent);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>