Matt Potter

Joined

220 Experience
2 Lessons Completed
0 Questions Solved

Activity

but what's the difference between using .find('[data=...]') vs just using a class of 'todo' or 'todo-toggle' etc on your element and using $('.todo') or $('.todo-toggle')? Same applies, you can still swap our a ul for a div or whatever and it would still work, you'd just have to move the class to your new element just as you would with the data-behaviour attribute. The only difference I can see is code aesthetics. In fact, using the css class as a selector could improve DRY as you're likely going to have to define a CSS class in order to style your todo, or todo-toggle etc anyway.

What's the functional difference between:

<div class="todo"></div>
$('.todo')....

and

<div data-behaviour="todo"></div>
$('[data-behaviour-id="todo"]')...

?

I'm not saying this approach is wrong, just that unless I missed something, I can't see what you gain. For me, it makes more sense that the definition of the type of the object/element, i.e. the class, should be in the class attribute, and the object/element specific data should be in data attributes. Effectively defining classes in a data attribute just seems a bit off to me.

Hmm... you're not really gaining anything over using a standard class selector though. I know in your example you start off by selecting on ul tag and directly referencing children etc, but you could just as easily get around that but adding classes and selecting those, rather than a data attribute.

I don't really see much benefit to using a data attribute as a selector, other than very minor aesthetic improvement (subjective, because I find the .find('[data-...]') syntax quite messy). The real benefits are in adding essential data for that individual object for referencing in your JS. I'm working on a project that is using polymorphic objects quite heavily, and I'm outputting my polymorphic_url to a data-update-url attribute for use in AJAX calls, for example.

Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

© 2024 GoRails, LLC. All rights reserved.