Skip to content
This repository was archived by the owner on Feb 4, 2018. It is now read-only.

Commit 5408901

Browse files
authored
Merge pull request #66 from bem-sdk/qfox.feat-tojson
feat: add toJSON method for good stringify
2 parents 2eb502a + 24c666a commit 5408901

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ API
106106
* [isBemEntityName(entityName)](#isbementitynameentityname)
107107
* [toString()](#tostring)
108108
* [valueOf()](#valueof)
109+
* [toJSON()](#tojson)
109110

110111
### constructor({ block, elem, mod })
111112

@@ -250,6 +251,10 @@ name.valueOf();
250251
// ➜ { block: 'button', mod: { name: 'focused', value: true } }
251252
```
252253

254+
### toJSON()
255+
256+
Returns object for `JSON.stringify()` purposes.
257+
253258
Debuggability
254259
-------------
255260

@@ -279,6 +284,19 @@ console.log(`name: ${name}`);
279284
// ➜ name: input_available
280285
```
281286

287+
Also `BemEntityName` has `toJSON` method to support `JSON.stringify()` behaviour.
288+
289+
```js
290+
const BemEntityName = require('@bem/entity-name');
291+
292+
const name = new BemEntityName({ block: 'input', mod: 'available' });
293+
294+
console.log(JSON.stringify(name));
295+
296+
// ➜ {"block":"input","mod":{"name":"available","val":true}}
297+
```
298+
299+
282300
License
283301
-------
284302

index.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,15 @@ module.exports = class BemEntityName {
240240
return `BemEntityName ${stringRepresentation}`;
241241
}
242242

243+
/**
244+
* Return raw data for `JSON.stringify()`.
245+
*
246+
* @returns {{block: string, elem: ?string, mod: ?{name: string, val: *}}}
247+
*/
248+
toJSON() {
249+
return this._data;
250+
}
251+
243252
/**
244253
* Determines whether specified entity is the deepEqual entity.
245254
*

test/to-json.test.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
const test = require('ava');
2+
3+
const BemEntityName = require('../index');
4+
5+
test('should return stringified cell', t => {
6+
const cell = new BemEntityName({ block: 'button' });
7+
8+
t.is(JSON.stringify([cell]), '[{"block":"button"}]');
9+
});

0 commit comments

Comments
 (0)