Ask A Question

Notifications

You’re not receiving notifications from this thread.

Clean Javascript Code Using Data-Behavior On The Frontend Discussion

Kohl Kohlbrenner Kohl Kohlbrenner

is data-behavior just semantics or could we use anything?

Reply

Great question. You could use anything you want, but it's good practice to use something like "data-behavior" because the naming gives a clear purpose for what it does.

Reply

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.

Reply
David Becerra  David Becerra 

I think you might have missed the point. The goal here isn't aesthetics, but rather the decoupling between your HTML structure and your JS. At the end of the video Chris completely changes the markup and everything still works. That's the benefit.

Reply
Kohl Kohlbrenner Kohl Kohlbrenner

@excid3:disqus can you recommend a good React tutorial?

Reply

This definitely better way to couple with html structure. I notice some people having another convention for css classes that will be used by javascript with `js-`. Have you had anything thought about that?

Reply

this would invoke the constructor on every page right ? is that ok or should one try to only run if the data-behavior is on the current page ?

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,329+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.