Skip to content

Commit

Permalink
Readme: describe enableInfiniteLoopDetection (fix #85)
Browse files Browse the repository at this point in the history
  • Loading branch information
mishanga committed Mar 16, 2015
1 parent 130e010 commit b6842e8
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 10 deletions.
28 changes: 23 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ There are two arguments provided to a template function:
* `ctx` – instance of `Ctx` class;
* `json` – link to a current BEMJSON tree node.

*NB*: Do not make changes directly in `json` object. Use methods of `ctx` object instead. We recommend you to use `json` object for reading only (see also `ctx.json()` method).
*N.B.* Do not make changes directly in `json` object. Use methods of `ctx` object instead. We recommend you to use `json` object for reading only (see also `ctx.json()` method).

Syntax:

Expand Down Expand Up @@ -193,7 +193,7 @@ bh.match('header', function(ctx) {
});
```
*NB*: Any non-undefined value will replace current node in BEMJSON tree. So you can delete current node just returning `null` value.
*N.B.* Any non-undefined value will replace current node in BEMJSON tree. So you can delete current node just returning `null` value.
Then wrap a content of `button` block with `content` element:
Expand Down Expand Up @@ -234,6 +234,24 @@ bh.match('button', function(ctx) {
});
```
## Infinite loop detection
The enableInfiniteLoopDetection method allows you to enable or disable the infinite loop detection process.
*N.B.* Enable the infinite loop detection in debugging mode only, because it slows down a template engine application.
```javascript
bh.enableInfiniteLoopDetection(true);
bh.match('button', function(ctx) {
ctx.content({ block: 'button' });
});
```
```
Error: Infinite matcher loop detected at "button".
```
# `Ctx` class
`Ctx` class instances are passed to all templates. All class methods in a set mode return the class instance.
Expand All @@ -250,7 +268,7 @@ bh.match('input', function(ctx) {
});
```
*NB*: If you set a value as `false` or as an empty string, the template will not put the current node to output HTML. The template will put only the content of this node if it exists.
*N.B.* If you set a value as `false` or as an empty string, the template will not put the current node to output HTML. The template will put only the content of this node if it exists.
## ctx.mod(key[, value[, force]])
Expand Down Expand Up @@ -291,7 +309,7 @@ bh.match('input_disabled_yes', function(ctx) {
});
```
*NB*: If an attribute is needed to be deleted and not nulled in its value, you have to pass `null` as a second parameter:
*N.B.* If an attribute is needed to be deleted and not nulled in its value, you have to pass `null` as a second parameter:
```javascript
bh.match('link', function(ctx) {
Expand Down Expand Up @@ -382,7 +400,7 @@ bh.match('input', function(ctx) {
Returns the current section of BEMJSON tree. You could use this class method with `return` method for wrapping. For brevity, you can use the second argument of the template function – `json`.
*NB*: The call of `ctx.applyBase()` function breaks the chain of consistent templates application. This causes the case when `json` stops to point out the current node in BEMJSON tree. To avoid this you must use `ctx.json()` method.
*N.B.* The call of `ctx.applyBase()` function breaks the chain of consistent templates application. This causes the case when `json` stops to point out the current node in BEMJSON tree. To avoid this you must use `ctx.json()` method.
```javascript
bh.match('input', function(ctx, json) {
Expand Down
27 changes: 22 additions & 5 deletions README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ bh.apply({ block: 'button' }); // '<button class="button"></button>'
Функции для работы с BEMJSON — **шаблоны** — объявляются через метод `match`. В теле функций описывается логика преобразования BEMJSON.
В функцию-шаблон передаются два аргумента: `ctx` — инстанция класса `Ctx` и `json` — ссылка на текущий узел BEMJSON-дерева.

*Замечание*: Категорически не рекомендуется вносить изменения напрямую в объект `json`. Вместо этого следует использовать методы объекта `ctx`. Объект `json` рекомендуется использовать только для «чтения» (см. также метод `ctx.json()`).
*Замечание:* Категорически не рекомендуется вносить изменения напрямую в объект `json`. Вместо этого следует использовать методы объекта `ctx`. Объект `json` рекомендуется использовать только для «чтения» (см. также метод `ctx.json()`).

Синтаксис:

Expand Down Expand Up @@ -184,7 +184,7 @@ bh.match('header', function(ctx) {
});
```
*Замечание*: Любое не-undefined значение вставляется в конечное BEMJSON-дерево вместо текущего узла. Соответственно, удалить текущий узел можно просто вернув значение `null`.
*Замечание:* Любое не-undefined значение вставляется в конечное BEMJSON-дерево вместо текущего узла. Соответственно, удалить текущий узел можно просто вернув значение `null`.
Обернем содержимое `button` элементом `content`:
Expand Down Expand Up @@ -222,6 +222,23 @@ bh.match('button', function(ctx) {
});
```
## Защита от зацикливания
Метод `enableInfiniteLoopDetection` позволяет включать и выключать механизм определения зацикливаний.
*Замечание:* Рекомендуется включать этот механизм только для отладки, так как он замедляет работу шаблонизатора.
```javascript
bh.enableInfiniteLoopDetection(true);
bh.match('button', function(ctx) {
ctx.content({ block: 'button' });
});
```
```
Error: Infinite matcher loop detected at "button".
```
# Класс `Ctx`
Expand All @@ -239,7 +256,7 @@ bh.match('input', function(ctx) {
});
```
*Замечание*: Если передать в качестве значения `false` или пустую строку, текущий узел не будет выведен в конечный HTML, выведется только его содержимое, если оно есть.
*Замечание:* Если передать в качестве значения `false` или пустую строку, текущий узел не будет выведен в конечный HTML, выведется только его содержимое, если оно есть.
## ctx.mod(key[, value[, force]])
Expand Down Expand Up @@ -280,7 +297,7 @@ bh.match('input_disabled_yes', function(ctx) {
});
```
*Замечание*: Если необходимо удалить сам атрибут, а не просто обнулить значение атрибута, то вторым параметром надо передать `null`:
*Замечание:* Если необходимо удалить сам атрибут, а не просто обнулить значение атрибута, то вторым параметром надо передать `null`:
```javascript
bh.match('link', function(ctx) {
Expand Down Expand Up @@ -369,7 +386,7 @@ bh.match('input', function(ctx) {
Возвращает текущий фрагмент BEMJSON-дерева. Может использоваться в связке с `return` для враппинга и подобных целей. Для сокращения можно использовать второй аргумент функции-шаблона — `json`.
*Замечание*: После вызова `ctx.applyBase()` нарушается цепочка естественного применения шаблонов. Из-за этого `json` перестает указывать на актуальный узел в BEMJSON-дереве. В этом случае следует использовать `ctx.json()`.
*Замечание:* После вызова `ctx.applyBase()` нарушается цепочка естественного применения шаблонов. Из-за этого `json` перестает указывать на актуальный узел в BEMJSON-дереве. В этом случае следует использовать `ctx.json()`.
```javascript
bh.match('input', function(ctx, json) {
Expand Down

0 comments on commit b6842e8

Please sign in to comment.