JS has a method Event.stopPropagation that here I will make the case introduces an anti-pattern to your code.
Here's the scenario:
user clicks submit on a form button, the code would look like the following:
submit.onclick = function(e) {
e.preventDefault() // similar method here
// .. do your thing
e.stopPropagation(); // stop furthering the event
}
1) Event occurs, and there is one file, and one method that the event is used.
Stopping event propagation here is nominal. This is a good use case, although it wouldn't make much difference to use stopPropagation.
2) You have multiple files that have multiple event listener methods.
Using stopEventPropagation should be avoided because it can act as an anti-pattern, here's how:
Let's say we have two different methods, and in two different files:
method1, file1
function eListener1(e, p) {
// tasks of eL1
}
and
method2, file2
function eListener2(e, p) {
// tasks of eL2
}
By definition, the layout of your code is completely different in the two scenarios .. one you're very much in the same place, and the other you leave to the great open yonder, not knowing exactly why or who is going to use something from somewhere as you're buidling.
To stop event propagation here is a mistake, and it would block tasks including delegation, and future use cases. For instance, suppose that your event is currently active in eL1 above; and now you want to create another event listener in another class or file that you will call eListener3 to perform some task on the same event. You would not be able to do this with stopPropagation; in effect you've limited your own possibilities, and another rate limiting step added to the soup is now that method that I will argue should have been avoided.
Stopping propagation is appropriate for a terminal event, such as deleting an item that has a known end; and not for general user interaction events. Signing out, for instance, could be another use case, however, would be redundant in many cases.
For general events, it's wasted energy. The consideration for stopEventPropagation at the general event level is perhaps at the heart of the rift between TCP or UDP versus TCP/IP.
In general, it's a good idea to avoid exotic methods unless you know exactly why you're using them. However, if you are building massively scaled TCP/IP request based systems that send large amounts of data, then this may not apply to you.
A potential or real benefit of stopEventPropagation is saving computing and/or bandwidth resources.So what's someone to do without stopping propagation?? Glad you asked, it's the simple conditional. The key here is to add a unique identifier to your object (i.e. this.supercalifradgilisticexpialidocious = 'here it is';), and in every one of your listeners you'd have your conditionals:
function eListener3(e, p) {
if (e === 'click') {
switch (p.foo.supercalifradgilisticexpialidocious) {
case 'here it is': {
// do func
break;
}
default: break;
}
}
}
No comments:
Post a Comment