CSS class names quickly get out of hand. Repos end up with unorganized CSS files all over the place making it difficult to name things and find them in the code.
The scoped components pattern addresses this by grouping classes into "component" scopes.
<div data-component="news-menu">
<h1 class="title">...</h1>
<ul class="items">
<li class="item">...</li>
...
</ul>
<aside id="breaking"></aside>
</div>
Now, when you want to write some code around the "News" box on your page, you can write everything in the context of the news component.
Instead of
$('#news-menu_breaking').click(function() {
$('.news-menu_get').html("Loading breaking news...");
});
$('.news-menu_item').click(function() {
$('#news-menu_loading-spinner').show();
location.href = $(this).data('url');
});
Define a scope
$.component('news-menu', function($scope) {
$scope('#breaking').click(function() {
$scope('.get').html("Loading breaking news...");
});
$scope('.item').click(function() {
$scope('#loading-spinner').show();
location.href = $scope(this).data('url');
});
});
See an example using jQuery or use the plugin
This also lets us keep css class names ultra simple. Instead of .news_menu-breaking
or .news_menu-title
, just use .breaking
or .title
keeping your code very readable without fear of it running into other classes.
[data-component="news-menu"] .title {
font-size: 18px;
font-family: helvetica, sans-serif;
}
Also see Amadeus