Already a lot has been said about BEM, what is good and what is bad, and we will not repeat today. Below is a story about how to work with BEM DOM from jQuery in small projects where conscience and time do not allow you to fasten bem-tools, bem-bl and bemhtml, but you still want to work with a convenient layout system, leaving behind long selectors in js files.<div class="b-product"> <div class="b-product__name">Coffe</div> <div class="b-product__price">$2</div> </div> <div class="b-product"> <div class="b-product__name">Tea</div> <div class="b-product__price">$1</div> </div> $('.b-product').first().children('.b-product__name'); // jQuery $('.b-product').first().elem('name'); // jQuery.BEM <div class="b-product">...</div> $('.b-product').setMod('theme', 'premium'); // .b-product.b-product_theme_premium $('.b-product').setMod('premium'); // .b-product.b-product_premium_yes <div class="b-product b-product_theme_premium">...</div> $('.b-product').delMod('theme', 'discount'); // - .b-product.b-product_theme_premium $('.b-product').delMod('theme', 'premium'); // .b-product_theme_premium $('.b-product').delMod('theme'); // theme <div class="b-product b-product_theme_premium">...</div> $('.b-product').getMod('theme'); // "premium" $('.b-product').getMod('discount'); // null <div class="b-product b-product_theme_premium">...</div> $('.b-product').hasMod('theme'); // true $('.b-product').hasMod('theme', 'premium'); // true $('.b-product').hasMod('theme', 'discount'); // false <div class="b-product b-product_theme_premium">...</div> <div class="b-product">...</div> $('.b-product').byMod('theme', 'premium'); // $('.b-product.b-product_theme_premium') $('.b-product').byMod('theme'); // $('.b-product.b-product_theme_premium') $('.b-product').byNotMod('theme'); // $('.b-product').not('.b-product_theme_premium') bem.decl('b-product', { onInit: function($this) { // price size large DOM // $this — jQuery $this.elem('price').setMod('size', 'large'); }, title: { onMouseover: function($this) { // b-product state hover $this.up().setMod('state', 'hover'); // - this._customFunction(); }, _customFunction: function() { console.log('I am helper function'); } }, price: { onSetmod: function($this, e, modKey, modVal) { // price console.log('Modifier set:', modKey, modVal); }, onDelmod($this, e, modKey, modVal) { // } } }); bem.decl({ block: 'b-product', mod: 'theme:premium'}, { // }); bem.decl({ block: 'b-product', elem: 'price' }, { // }); bem.setConfig({ namePrefix: '', // , elemPrefix: '-', // modPrefix: '_', // modDlmtr: '-' // }); .block .block-element .block-element_modifier-value Source: https://habr.com/ru/post/196368/
All Articles