Skip to content

Instantly share code, notes, and snippets.

@think49
Last active July 13, 2017 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save think49/a2a91f34bb947b3b5a841fd8b4d3342a to your computer and use it in GitHub Desktop.
Save think49/a2a91f34bb947b3b5a841fd8b4d3342a to your computer and use it in GitHub Desktop.
virtual-dom.js: DOM API互換の Interface で仮想DOMオブジェクトを生成する

virtual-dom.js

概要

DOM API互換の Interface で仮想DOMオブジェクトを生成する。

使い方

p要素ノードを生成し、id属性値を付与する。

var p = new Element('p');
p.id = 'foo';

div要素ノードにp要素ノードを appendChild する。

var div = new Element('div'),
    p = new Element('p');

div.appendChild(p);
console.log(p.parentNode === div);  // true
console.log(div.children[0] === p); // true

使用可能なDOM API一覧

  • Node.prototype.ELEMENT_NODE
  • Node.prototype.TEXT_NODE
  • Node.prototype.nodeType
  • Node.prototype.appendChild
  • Node.prototype.parentNode
  • Element.prototype.tagName
  • Element.prototype.id
  • Element.prototype.children
/**
* virtual-dom.js
*
* @version 0.1.0
* @author think49
* @url https://gist.github.com/think49/a2a91f34bb947b3b5a841fd8b4d3342a
* @license http://www.opensource.org/licenses/mit-license.php (The MIT License)
*/
var VirtualDOM = (function (defineProperties, String, WeakMap, Map) {
'use strict';
var privateMap = new WeakMap;
function Node () {}
defineProperties(Node.prototype, {
ELEMENT_NODE: {enumerable: true, value: 1},
TEXT_NODE: {enumerable: true, value: 3},
nodeType: {configurable: true, enumerable: true, get: function () {
return privateMap.get(this).get('nodeType');
}},
parentNode: {configurable: true, enumerable: true, get: function () {
return privateMap.get(this).get('parentNode');
}},
appendChild: {configurable: true, enumerable: true, writable: true,
value: function appendChild (childNode) {
privateMap.get(childNode).set('parentNode', this);
privateMap.get(this).get('children').push(childNode);
}}
});
function Element (tagName) {
privateMap.set(this, new Map([
['nodeType', Node.prototype.ELEMENT_NODE],
['tagName', String(tagName)],
['children', []],
['id', ''],
['parentNode', null]
]));
}
Element.prototype = new Node;
defineProperties(Element.prototype, {
tagName: {configurable: true, enumerable: true,
get: function () { return privateMap.get(this).get('tagName'); },
set: function (value) { return privateMap.get(this).set('tagName', String(value)); }
},
id: {configurable: true, enumerable: true,
get: function () { return privateMap.get(this).get('id'); },
set: function (value) { return privateMap.get(this).set('id', String(value)); }
},
children: {configurable: true, enumerable: true,
get: function () { return privateMap.get(this).get('children'); }
}
});
return {Node: Node, Element: Element};
}.call(this, Object.defineProperties, String, WeakMap, Map));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment