Clean Javascript Code Using Data-Behavior On The Frontend Discussion
is data-behavior just semantics or could we use anything?
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.
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.
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.
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?
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 ?