Skip to content

Commit

Permalink
Merge pull request #83 from enb-bem/issue-80
Browse files Browse the repository at this point in the history
Added `scope` option to `bh-bundle` tech
  • Loading branch information
blond committed May 25, 2015
2 parents e0f3e4b + fd133f8 commit cb7f17c
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ $ npm install --save-dev enb-bh
* *String* **filesTarget** — files-таргет, на основе которого получается список исходных файлов (его предоставляет технология `files`). По умолчанию — `?.files`.
* *String* **sourceSuffixes** — суффиксы файлов, по которым строится `files`-таргет. По умолчанию — `['bh.js']`.
* *Boolean* **sourcemap** — строить карты кода.
* *String* **scope** — скоуп выполнения кода шаблонов. По умолчанию — `template`. Если значение равно `template`, то каждый шаблон будет выполнен в своём отдельном скоупе. Если значение равно `global`, то все шаблоны будут выполнены в общем скоупе.
* *String|Array* **mimic** — имена переменных для экспорта.
* *String* **jsAttrName** — атрибут блока с параметрами инициализации. По умолчанию — `data-bem`.
* *String* **jsAttrScheme** — Схема данных для параметров инициализации. По умолчанию — `json`. Форматы: `js` — Получаем `return { ... }`. `json` — JSON-формат. Получаем `{ ... }`.
Expand Down
6 changes: 4 additions & 2 deletions lib/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ core.contents = fs.readFileSync(core.path, 'utf-8');
* @param {String} [opts.jsAttrName] Use `jsAttrName` option for bh core
* @param {String} [opts.jsAttrScheme] Use `jsAttrScheme` option for bh core
* @param {String} [opts.jsCls] Use `jsCls` option for bh core
* @param {String} [opts.scope=template] Scope of the executing code templates
* @param {String[]} [opts.mimic] Names for exports
* @param {Object} [opts.dependencies] Names for requires to `BH.lib.name`
* @returns {String} compiled code of bh module
Expand All @@ -33,6 +34,7 @@ function compile(sources, opts) {
}

var file = new File(opts.filename, opts.sourcemap),
isTemplateScope = opts.hasOwnProperty('scope') ? opts.scope === 'template' : true,
mimic = opts.mimic || [],
dependencies = opts.dependencies || {},
depNames = Object.keys(dependencies);
Expand All @@ -59,11 +61,11 @@ function compile(sources, opts) {
var relPath = source.relPath || source.path;

// wrap in IIFE to perform each template in its scope
file.writeLine('(function () {');
isTemplateScope && file.writeLine('(function () {');
file.writeLine('// begin: ' + relPath);
file.writeFileContent(source.path, source.contents);
file.writeLine('// end: ' + relPath);
file.writeLine('}());');
isTemplateScope && file.writeLine('}());');
});
file.writeLine('}());');

Expand Down
5 changes: 5 additions & 0 deletions techs/bh-bundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
* (его предоставляет технология `files`). По умолчанию — `?.files`.
* * *String* **sourceSuffixes** — суффиксы файлов, по которым строится `files`-таргет. По умолчанию — ['bh.js'].
* * *Boolean* **sourcemap** — строить карты кода.
* * *String* **scope** — скоуп выполнения кода шаблонов. По умолчанию — `template`. Если значение равно `template`,
* то каждый шаблон будет выполнен в своём отдельном скоупе. Если значение равно `global`,
* то все шаблоны будут выполнены в общем скоупе.
* * *String|Array* **mimic** — имена переменных/модулей для экспорта.
* * *String* **jsAttrName** — атрибут блока с параметрами инициализации. По умолчанию — `data-bem`.
* * *String* **jsAttrScheme** — Cхема данных для параметров инициализации. По умолчанию — `json`.
Expand Down Expand Up @@ -49,6 +52,7 @@ module.exports = require('enb/lib/build-flow').create()
.defineOption('jsCls', 'i-bem')
.defineOption('escapeContent', false)
.defineOption('sourcemap', false)
.defineOption('scope', 'template')
.useFileList(['bh.js'])
.builder(function (files) {
return this._readTemplates(files)
Expand All @@ -72,6 +76,7 @@ module.exports = require('enb/lib/build-flow').create()
jsAttrScheme: this._jsAttrScheme,
jsCls: this._jsCls,
escapeContent: this._escapeContent,
scope: this._scope,
mimic: [].concat(this._mimic),
dependencies: this._dependencies
};
Expand Down
12 changes: 12 additions & 0 deletions test/techs/bh-bundle/bh-bundle.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ describe('bh-bundle', function () {

return assert(bemjson, html, templates);
});

it('must perform each template in common scope if `scope: global`', function () {
var templates = [
'var text = "Hello world!";',
'bh.match("block", function(ctx) {ctx.content(typeof text === "undefined" ? "Hi!" : text);});'
],
bemjson = { block: 'block' },
html = '<div class="block">Hello world!</div>',
opts = { scope: 'global' };

return assert(bemjson, html, templates, opts);
});
});

describe('jsAttr params', function () {
Expand Down

0 comments on commit cb7f17c

Please sign in to comment.