freefaller freefaller - 1 year ago 79
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

var allObj = [];
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 Source

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
  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=""></script>