Answer the question
In order to leave comments, you need to log in
Is it true that top-level elements should control lower-level elements and not vice versa?
There was a dispute with a colleague, he argues that the top-level elements in the DOM tree should control the lower ones and nothing else, i.e. walking up a tree is bad practice. For example, bad practice, in his opinion:
$(document).on('click', 'button', function() {
$(this).closest('.wrapper').addClass('selected');
});
$('.wrapper').each(function() {
var item = $(this);
item.find('button').click(function() {
item.addClass('selected');
});
});
Answer the question
In order to leave comments, you need to log in
Instead, he argues, we should track the events of external elements and change internal ones.
we have to track the events of external elements and change internal ones.
If we talk about OOP and programming, then your interlocutor is right.
The upper level should directly change the lower ones, and those, in turn
, should send events to which the higher ones may or may not react.
And I don't know who created jQuery, but I can only say one thing,
not one html -> css -> js developer does not know and does not fully understand the principles and basics of programming.
I can add on my own that what is considered the norm in software development and game development, is considered stupid and ridiculous on the web and is justified only by the fact that "I don't do that." All the innovations that appear in recent times are made by java -> c programmers ...
What can I say, even if mvc for sites is not the same as for online games.
There are a number of tasks that cannot be solved from top to bottom. You pointed at once and a counter-example:) change of the parent, in connection with action in the descendant. It seems to me that also because not everything is possible in css, such a strong library for DOM manipulation as jQuery appeared. And while it has methods like .closest(), you should not bother about "Orthodoxy". Especially if otherwise it doesn’t matter, either it’s impossible, or it’s possible, but much more troublesome.
The Orthodox method is to hang a listener on the parent and determine the child by the target.
In doing so, jQuery saves the element that triggered the event to the delegateTarget variable of the event object.
To paraphrase:
$('.wrapper').on('click', 'button', function(event) {
$(event.delegateTarget).addClass('selected');
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question