Last active
October 30, 2017 10:51
-
-
Save eonarik/f6565acdbc50d9cacf818f31071a9926 to your computer and use it in GitHub Desktop.
function toPH
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Object.prototype.toPH = function () { | |
if (typeof this.ns === 'undefined') { | |
return; | |
} | |
// обходим свойства | |
for (let key in this.data) { | |
let prop = this.data[key]; | |
let _this = this; | |
if (typeof prop === 'function') { | |
continue; | |
} | |
Object.defineProperty(this.data, key, { | |
set: function (value) { | |
// находим в DOM элемент c неймспейсом как у текущего объекта | |
let selectorNS = '[data-ns="' + _this.ns + '"]'; | |
let nodesList = document.querySelectorAll(selectorNS); | |
// обходим все что нашли | |
for (let j = 0; j < nodesList.length; j++) { | |
// найдем внутренние теги с нужным аттрибутом data-ph | |
let selector = '[data-ph="' + key + '"], [data-ph*=",' + key + '"], [data-ph*=",' + key + ',"],[data-ph*="' + key + ',"]'; | |
let phs = nodesList[j].querySelectorAll(selector); | |
for (var k = 0; k < phs.length; k++) { | |
let ph = phs[k]; | |
let keys = ph.getAttribute('data-ph').split(','); | |
let index = 0; | |
for (let i = 0; i < keys.length; i++) { | |
if (key == keys[i]) { | |
index = i; | |
} | |
} | |
// если value массив | |
if (Array.isArray(value)) { | |
// находим первый внутренний тег | |
let node = ph.children[0].cloneNode(true); | |
ph.innerHTML = ''; | |
// и добавляем дубликаты этого тега в кол-ве равным кол-ву элементов массива | |
for (var i = 0; i < value.length; i++) { | |
let newNode = node.cloneNode(true); | |
let nsName = key + '-' + i; | |
let obj = { | |
ns: nsName, | |
data: value[i], | |
}; | |
newNode.setAttribute('data-ns', nsName); | |
ph.appendChild(newNode); | |
obj.toPH(); | |
} | |
} else { | |
// если указан атрибут назначения data-ph-target | |
if (ph.hasAttribute('data-ph-target')) { | |
let targets = ph.getAttribute('data-ph-target').split(','); | |
if (typeof targets[index] !== 'undefined' && targets[index]) { | |
ph.setAttribute(targets[index], value); | |
} else { | |
// если указан атрибут data-ph-html | |
if (ph.hasAttribute('data-ph-html')) { | |
ph.innerHTML = value; | |
} else { | |
ph.textContent = value; | |
} | |
} | |
} else { | |
// если указан атрибут data-ph-html | |
if (ph.hasAttribute('data-ph-html')) { | |
ph.innerHTML = value; | |
} else { | |
ph.textContent = value; | |
} | |
} | |
} | |
} | |
} | |
}, | |
get: function () { | |
return prop; | |
} | |
}); | |
// для начального заполнения, если у объекта уже есть определенное свойство - оно отобразится | |
if (this.data[key]) { | |
this.data[key] = this.data[key]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment