2

I want to implement custom event with this functionality:

  • create custom event
  • after callback of ajax dispatch event
  • any object in document (div, grid, ...) can register listener of this custom event
  • when event is fired, all objects which have registered listener event call any methods

I tried created custom event (no problem):

var eventFilterRefresh = document.createEvent("CustomEvent");
eventFilterRefresh.initEvent("onFilterCancel", true, true);

Register event:

var dv = document.getElementById('myDiv');
dv.addEventListener('onFilterCancel', function (e) {
    alert();
}, false);

Dispatch event - here is problem. I don't wont call dispatchEvent on conrete object. I want call generaly dispatchEvent and all objects which have registered event makes methods:

var myDiv= document.getElementById('myDiv');
myDiv.dispatchEvent(eventFilterCancel);

Thanks.

1
  • Perhaps a pubsub library is what you need? Commented Feb 26, 2015 at 7:56

1 Answer 1

2

There is no way to fire an event from a single context so that listeners bound to a variety of other elements will trigger on it. You will need to fire the event from the context of each of the elements with the relevant listener.

The easiest way to do this is to add a hook like a class name to all of the elements that have the event listener and then use that hook to dispatch the event for each element.

//Add a hook when you register the listener
var dv = document.getElementById('myDiv');
dv.addEventListener('onFilterCancel', function (e) {
    alert();
}, false);
dv.className += " js-filter-cancel";

//Use the hook to fire the event for all listeners
var myDivs= document.querySelectorAll('.js-filter-cancel');

for(var i in myDivs) {
  if(!myDivs.hasOwnProperty(i))
    continue;
  
  myDivs[i].dispatchEvent(eventFilterCancel);
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.