Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add global matcher #121

Closed
dosyara opened this issue Mar 12, 2015 · 13 comments · Fixed by #139
Closed

Add global matcher #121

dosyara opened this issue Mar 12, 2015 · 13 comments · Fixed by #139

Comments

@dosyara
Copy link
Member

dosyara commented Mar 12, 2015

For extension purposes of BH-core functionality it wood be good to have API to set global matcher. This matcher must be executed on each BEMJSON-node to make necessary modifications.
As I understand, it's possible to want to execute some code before and after other user matchers. So, probably, we need beforeEach and afterEach kind of matchers.

@mishanga
Copy link
Member

Предлагаемый синтаксис:
beforeEach: bh.match('<', function(ctx) { ... })
afterEach: bh.match('>', function(ctx) { ... })

@mishanga
Copy link
Member

Второй вариант:
bh.beforeEach(function(ctx) { ... })
bh.afterEach(function(ctx) { ... })

@sameoldmadness
Copy link
Contributor

Я за второй вариант. По нему можно догадаться, что происходит, не заглядывая в документацию.

@qfox
Copy link
Member

qfox commented Mar 26, 2015

Все-таки решились на это? ;-\

@tadatuta
Copy link
Member

Предлагаю в этом месте сделать консистентно с BEMHTML:

bh.match(function() {}, function() {});

смотреть в typeof первого аргумента и если там функция, выполнять шаблон только для кейсов, когда она возвращает truly-значение.

@dosyara
Copy link
Member Author

dosyara commented Mar 26, 2015

Это же нельзя делать консистентно c BEMHTML, у шаблонизаторов разная "механика". У BH нет нигде подобного паттерна.

@tadatuta
Copy link
Member

@dosyara
Разве с точки зрения механики

bh.match(function(ctx) {
    return ctx === 'bla';
}, function(ctx) { doSomething(); });`

чем-то отличается от

bh.beforeEach(function(ctx) {
   if (ctx === 'bla') doSomething();
});

?

@qfox
Copy link
Member

qfox commented Mar 26, 2015

Там не все так просто, не получится смотреть в typeof.
Из этих матчеров собираются switch-case, и при добавлении матчера оно сбрасывает «кеш» собранных свичкейсов и пересобирает его при следующем вызове apply.

Т.е. ты прав, но этот function должен будет отрабатывать в switch-case, а с учетом того, что порядок играет — я не очень себе представляю, как это должно будет работать так, что результат был ожидаемым. Может я перебдел, конечно, но пока кажется, что это просто нереально.

Но даже если я не прав в предыдущем — то beforeEach — это последний матчер, afterEach — первый, но

  • Не выйдет их доопределять (как гарантировать, что afterEach всегда будет вызываться?);
  • Будут сложности со сборкой (как гарантировать, что beforeEach всегда будет последним?).

Пара проблем из тех, которые, кмк, не позволяют это сделать.

@mishanga
Copy link
Member

@tadatuta @zxqfox все шаблоны перед запуском компилируются примерно в такую конструкцию:

function applyMatchers(ctx, json) {
    subRes = _m2(ctx, json); // beforeEach
    switch (json.block) {
       case "button":
           switch (json.elem) {
               case undefined:
                   subRes = _m0(ctx, json); // match('button')
           }
       }
    }         
    subRes = _m1(ctx, json); // afterEach
};

То есть там получается один большой switch, в который нельзя добавить глобальный шаблон. Можно только перед switch или после. Но для разных задач нужен разный порядок исполнения: где-то глобальный шаблон должен применяться до всех остальных, где-то после. Поэтому пришлось сделать явное разделение на beforeEach и afterEach.

qfox pushed a commit to bem/bh-php that referenced this issue Apr 23, 2015
- Added global matcher support: `beforeEach` and `afterEach` (bem/bh#121).
- Added `ctx.process` method (bem/bh#135).
- Add `i-bem` class to element with `js` (bem/bh#122).
- No-base modifier classes supported (bem/bh#132).
- `processBemJson` now return standart BEMJSON (bem/bh#96).

Changelog bem/bh@ee446ea
qfox pushed a commit to bem/bh-php that referenced this issue Apr 23, 2015
- Added global matcher support: `beforeEach` and `afterEach` (bem/bh#121).
- Added `ctx.process` method (bem/bh#135).
- Add `i-bem` class to element with `js` (bem/bh#122).
- No-base modifier classes supported (bem/bh#132).
- `processBemJson` now return standart BEMJSON (bem/bh#96).

Changelog bem/bh@ee446ea
qfox pushed a commit to bem/bh-php that referenced this issue Apr 23, 2015
- Added global matcher support: `beforeEach` and `afterEach` (bem/bh#121).
- Added `ctx.process` method (bem/bh#135).
- Add `i-bem` class to element with `js` (bem/bh#122).
- No-base modifier classes supported (bem/bh#132).
- `processBemJson` now return standart BEMJSON (bem/bh#96).

Changelog bem/bh@ee446ea
qfox pushed a commit to bem/bh-php that referenced this issue Apr 23, 2015
- Added global matcher support: `beforeEach` and `afterEach` (bem/bh#121).
- Added `ctx.process` method (bem/bh#135).
- Add `i-bem` class to element with `js` (bem/bh#122).
- No-base modifier classes supported (bem/bh#132).
- `processBemJson` now return standart BEMJSON (bem/bh#96).

Changelog bem/bh@ee446ea
@gruzzilkin
Copy link

А можно дополнить README с описанием и примером применения этой фичи? @zxqfox

@qfox
Copy link
Member

qfox commented Aug 30, 2015

@gruzzilkin Есть предложение что написать в ридми? ;)

@gruzzilkin
Copy link

@zxqfox Например, что данные методы можно использовать для преобразования входящего JSON в BEMJSON и последующим применением шаблонов bh. Т.е. по сути с помощью beforeEach можно делать то же самое, что и с помощью bemtree.

@mishanga
Copy link
Member

Про это даже есть issue: #142
Но у меня руки не доходят.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants