Skip to content

Instantly share code, notes, and snippets.

@aziis98
Last active August 16, 2016 23:18
Show Gist options
  • Save aziis98/dc6bdede5921d2918c6152359ccc4e74 to your computer and use it in GitHub Desktop.
Save aziis98/dc6bdede5921d2918c6152359ccc4e74 to your computer and use it in GitHub Desktop.
A small library that adds a template engine and a one way binding mechanism. All in about 100 lines of code. (TODO: Add list/objects iterators)
/*
A small library that adds a template engine and a one way binding mechanism. All in 200 lines of code.
*/
RegExp.escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
(function (exports) {
//noinspection UnnecessaryLocalVariableJS
var PocketBinder = {
options: {
dataTagLeft: '{{',
dataTagRight: '}}'
},
eval: function (scope, action) {
return function () {
return eval(action)
}.call(scope)
},
from: function (selector) {
var node = document.querySelector(selector)
var model = {}
model.render = compileTemplate(node, model)
attachListeners(node, model)
return model
}
}
function attachListeners(node, model) {
var dataModels = node.querySelectorAll('[data-model]')
dataModels.forEach(function (modelNode) {
const modelTarget = modelNode.getAttribute('data-model')
if (modelNode.tagName.toLowerCase() == 'input') {
if (modelNode.getAttribute('type') == 'text') {
PocketBinder.eval(model, 'this.' + modelTarget + ' = "' + modelNode.value + '"')
modelNode.onkeyup = function () {
PocketBinder.eval(model, 'this.' + modelTarget + ' = "' + modelNode.value + '"')
model.render()
}
modelNode.onkeydown = function () {
// model.render()
}
}
else if (modelNode.getAttribute('type') == 'number') {
PocketBinder.eval(model, 'this.' + modelTarget + ' = "' + modelNode.value + '"')
modelNode.oninput = function () {
PocketBinder.eval(model, 'this.' + modelTarget + ' = "' + modelNode.value + '"')
model.render()
}
}
}
}.bind(model))
node.querySelectorAll('[data-event-click]').forEach(function (node) {
var action = node.getAttribute('data-event-click')
node.onclick = function (e) {
eval(action)
}.bind(model)
})
}
function compileTemplate(node, model) {
var regex = new RegExp(RegExp.escape(PocketBinder.options.dataTagLeft) + '(.+?)' + RegExp.escape(PocketBinder.options.dataTagRight), 'g')
const TYPE_TEXT = 3
const TYPE_ELEMENT = 1
function expandTemplate(node, model) {
var newNode = node.cloneNode(false)
if (newNode.nodeType == TYPE_TEXT) {
newNode.nodeValue = newNode.nodeValue.replace(regex, function (match, inside) {
return PocketBinder.eval(model, inside)
})
}
else if (newNode.nodeType == TYPE_ELEMENT) {
for (var i = 0; i < newNode.attributes.length; i++) {
const attr = newNode.attributes.item(i)
const templateValue = attr.nodeValue
if (attr.nodeValue.indexOf(PocketBinder.options.dataTagLeft) != -1) {
attr.nodeValue = templateValue.replace(regex, function (match, inside) { return PocketBinder.eval(model, inside) })
}
}
node.childNodes.forEach(function (child) { newNode.appendChild(expandTemplate(child, model)) })
}
return newNode
}
function compileNodeRec(node, renderFunctions, model) {
if (node.nodeType == TYPE_TEXT) {
const templateValue = node.nodeValue
if (templateValue.indexOf(PocketBinder.options.dataTagLeft) != -1) {
renderFunctions.push(function () {
node.nodeValue = templateValue.replace(regex, function (match, inside) { return eval(inside) }.bind(model))
})
}
}
else if (node.nodeType == TYPE_ELEMENT) {
for (var i = 0; i < node.attributes.length; i++) {
const attr = node.attributes.item(i)
const templateValue = attr.nodeValue
if (attr.nodeName.indexOf('data-repeat-') == 0) {
console.log(attr.nodeName)
const template = node.cloneNode(true)
renderFunctions.push(function () {
var list = PocketBinder.eval(model, attr.nodeValue)
const localVarName = attr.nodeName.split('-')[2]
while (node.firstChild) {
node.removeChild(node.firstChild)
}
var index = 0
if (list.forEach) {
list.forEach(function (element) {
var submodel = { }
submodel.__proto__ = model
submodel[localVarName] = element
submodel['__index'] = index
index++
var expandedNode = expandTemplate(template, submodel) // .childNodes
while (expandedNode.firstChild) {
node.appendChild(expandedNode.firstChild)
}
})
}
else {
const localVarValue = localVarName
const localVarKey = attr.nodeName.split('-')[3]
for (var key in list) {
if (list.hasOwnProperty(key)) {
var submodel = { }
submodel.__proto__ = model
submodel['__index'] = index
submodel[localVarKey] = key
submodel[localVarValue] = list[key]
index++
var expandedNode = expandTemplate(template, submodel) // .childNodes
while (expandedNode.firstChild) {
node.appendChild(expandedNode.firstChild)
}
}
}
}
})
}
if (attr.nodeValue.indexOf(PocketBinder.options.dataTagLeft) != -1) {
renderFunctions.push(function () {
attr.nodeValue = templateValue.replace(regex, function (match, inside) { return eval(inside) }.bind(model))
})
}
}
node.childNodes.forEach(function (child) { compileNodeRec(child, renderFunctions, model) })
}
}
var renderFunctions = []
compileNodeRec(node, renderFunctions, model)
return function () {
renderFunctions.forEach(function (func) { func() })
}
}
exports.PocketBinder = PocketBinder
})(window)
<!doctype html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Binder.js</title>
</head>
<body>
<div class="container">
<h1>Hello [[ this.name ]]!</h1>
<label>
Name:
<input type="text" data-model="name" value="Orlando">
</label>
<br>
<br>
<div class="list"
data-repeat-person="this.people">
[[ (Number(this.__index) + Number(this.a)) ]]
<div class="item" id="item[[ this.__index ]]">
[[ this.person ]]
</div>
</div>
<div class="list" data-repeat-value-key="this.obj">
[[ this.key ]] - [[this.value]]
</div>
<br>
<br>
<label>
a:
<input type="number" data-model="a">
</label>
<br>
<label>
b:
<input type="number" data-model="b">
</label>
<p>The product of those two numbers is : [[ Number(this.a) * Number(this.b) ]]</p>
<button data-event-click="this.mybutton()">Bottone</button>
</div>
<script src="binder.js"></script>
<script>
PocketBinder.options.dataTagLeft = '[['
PocketBinder.options.dataTagRight = ']]'
var model = PocketBinder.from('.container')
model.people = [
'Person1', 'Person2', 'Person3', 'Person4', 'Person5'
]
model.obj = {
a: 1,
b: 2,
c: 3
}
model.mybutton = function () {
model.people.push('New Person')
model.render()
}
model.render()
</script>
</body>
</html>
MIT License
Copyright (c) 2016 Antonio de Lucreziis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment