

Tips for how to decouple your HTML, CSS, and JavaScript - philipwalton
http://philipwalton.com/articles/decoupling-html-css-and-javascript/

======
SchizoDuckie
Why promote the (ab)use of the class attribute for binding user interface
behavior?

It's 2013, people that write blogposts should be directing their readers (imo)
to using the (html5) data-* attributes (which works equally simple) and
actually removes the declaration and mixture of behavior and styling from your
css.

For instance your button example:

    
    
        <button data-behavior='addtocart' data-somespecialparameter='iamspecial' class="add-item">Add to Cart</button>
    

Would behave on some javascript:

jQuery:

    
    
        $(document.body).on('click' 'button[data-behavior="addtocart"]', myHandlerFunction);
    

MooTools

    
    
        document.body.addEvent('click:relay(button[data-behavior="addtocart"])', myHandlerFunction);
    

Handler:

    
    
        function myHandlerFunction(ev) {
          console.log("I just got clicked. ", this.getAttribute('data-somespecialparameter'), this);
        }
    

Also, using observers on a container element makes sure that you can
dynamically add and remove html elements without having to worry about
cleaning up the even handlers. (binding it all on document.body or the nearest
container can be debatable for speed reasons, but this is up to you)

~~~
philipwalton
I tend to be pretty picky in following the spec and only use HTML data-*
attributes for actually passing data. That being said, I think it’s mainly a
matter of personal preference. If the data-* attributes method makes more
sense to you and your team, by all means use it.

I should note, though, that if performance is a concern, traversing the DOM
for classes is significantly faster than for attributes. Here’s a jsperf
example I put together a while back comparing the two:
[http://jsperf.com/class-vs-data-attribute-selector-
performan...](http://jsperf.com/class-vs-data-attribute-selector-performance)

Lastly, it's worth pointing out that it is still possible to style elements
with attributes in CSS, so the data-* attribute approach doesn't actually
prevent coupling between style and behavior, it's just another convention
(like js-* prefixed classes). In both cases it's still up to you to enforce
the convention.

