1

Similar to this question about jQuery custom events, I'm trying to find out what the effect of return false; is, with the exception that I am not using jQuery. I'm triggering a custom event via the following method:

var event = document.createEvent('Event');
event.initEvent('CustomName', false, true);
element.dispatchEvent(event);

This is wrapped in a function, and I return the event object after dispatching the event. Now, I'm looking for a way in the triggering code to see if one of the listeners returned false so that I can prevent further execution. How would I be able to detect if one of the listeners returned false in a cross-browser manner (IE 7+)?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
LoveAndCoding
  • 7,857
  • 2
  • 31
  • 55
  • possible duplicate of [What does "return false;" do?](http://stackoverflow.com/questions/10729198/what-does-return-false-do). Read the comment by T.J. Crowder in the answer. – gdoron Jan 03 '13 at 21:59
  • @gdoron Yes, that is what happens for Vanilla JS events. I know that. This isn't about vanilla JS events, but vanilla JS custom events. There is no default to prevent. My question is about what is the effect on a custom event object and how can I detect it, not on any generic event. – LoveAndCoding Jan 03 '13 at 22:04

1 Answers1

1

It specifies if the created event will bubble through or not

(EDIT) consider the following example:

var evt = document.createEvent('Event');
evt.initEvent('myevent', true, true); // the third argument here specifies whether the event can be cancelled
var elem = document.getElementById('mydiv');
elem.addEventListener('myevent', function(e){
    e.preventDefault();
}, true);
console.log(elem.dispatchEvent(evt)); //Here you will get return value of false because in the event handler you called e.preventDefault()

The problem is that you want it to work with IE 7+ but IE 7 and 8 don't support document.createEvent in the first place

Vlad Lyga
  • 1,133
  • 9
  • 10
  • Read the answer to the question linked in comments above, and you'll actually see that it does not prevent bubble. In some browsers, `return false;` will prevent default, but not in all cases. – LoveAndCoding Jan 03 '13 at 22:35
  • Well, I am sorry but I think you're wrong. Refer to the [following doc page at MDN on the initEvent mehtod] (https://developer.mozilla.org/en-US/docs/DOM/event.initEvent) You shouldn't have down voted my answer. – Vlad Lyga Jan 03 '13 at 22:39
  • I'm not sure what on that page show's you are correct. The `initEvent` method is used to specify if an event should bubble, or can be cancelled, but it makes no indication of the effect of the return value from a listener. – LoveAndCoding Jan 03 '13 at 22:43
  • Ok @Ktash, I re-red your question and I hope I understand what do you want. I added some code to my edited answer. – Vlad Lyga Jan 03 '13 at 23:08