e63ff384 by Nicklas Ansman Giertz

Merge remote-tracking branch 'upstream/master' into feature/tests

Conflicts:
	build/rivets.js
	src/rivets.coffee
2 parents 9b284cf9 b5e51cfc
# Rivets.js
Rivets.js is a declarative, observer-based DOM-binding facility that plays well with existing frameworks such as [Backbone.js](http://backbonejs.org), [Spine.js](http://spinejs.com) and [Stapes.js](http://hay.github.com/stapes/). It aims to be lightweight (1.2KB minified and gzipped), extensible, and configurable to work with any event-driven model.
Rivets.js is a declarative data binding facility that plays well with existing frameworks such as [Backbone.js](http://backbonejs.org), [Spine.js](http://spinejs.com) and [Stapes.js](http://hay.github.com/stapes/). It aims to be lightweight (1.2KB minified and gzipped), extensible, and configurable to work with any event-driven model.
---
Describe your UI directly in the DOM using data attributes:
Describe your UI in plain HTML using data attributes:
<div id='auction'>
<h1 data-text='auction.title'></h1>
......@@ -28,11 +28,11 @@ Describe your UI directly in the DOM using data attributes:
</dl>
</div>
Then tell Rivets.js what model(s) to bind to what part of the DOM:
Then tell Rivets.js what model(s) to bind to it:
rivets.bind($('auction'), {auction: auction, user: currentUser});
rivets.bind($('#auction'), {auction: auction, user: currentUser});
## Configuring
## Configure
Use `rivets.configure` to configure Rivets.js for your app. There are a few handy configuration options, such as setting the data attribute prefix and adding formatters that you can pipe binding values to, but setting the adapter is the only required configuration since Rivets.js needs to know how to observe your models for changes as they happen.
......@@ -75,9 +75,9 @@ To prevent data attribute collision, you can set the `prefix` option to somethin
Set the `preloadData` option to `true` or `false` depending on if you want the binding routines to run immediately after the initial binding or not — if set to false, the binding routines will only run when the attribute value is updated.
## Extending
## Extend
You can extend Rivets.js by adding your own custom data bindings (routines). Just pass `rivets.register` an identifier for the routine and routine function. Routine functions take two arguments, `el` which is the DOM element and `value` which is the incoming value of the attribute being bound to.
You can extend Rivets.js by adding your own custom data bindings (routines). Just pass `rivets.register` an identifier and a routine function. Routine functions take two arguments, `el` which is the DOM element and `value` which is the incoming value of the attribute being bound to.
So let's say we wanted a `data-color` binding that sets the element's colour. Here's what that might look like:
......@@ -97,4 +97,5 @@ So let's say we wanted a `data-color` binding that sets the element's colour. He
- data-checked
- data-unchecked
- data-selected
- data-[attribute]
\ No newline at end of file
- data-*[attribute]*
- data-on-*[event]*
\ No newline at end of file
......
(function(){var m,c,d,g,i,h,n,f,j=function(b,a){return function(){return b.apply(a,arguments)}},o=[].indexOf||function(b){for(var a=0,p=this.length;a<p;a++)if(a in this&&this[a]===b)return a;return-1};g=d=c=m=void 0;m=function(){function b(a,b,e,l,k){this.el=a;this.type=b;this.model=e;this.keypath=l;this.formatters=null!=k?k:[];this.unbind=j(this.unbind,this);this.publish=j(this.publish,this);this.bind=j(this.bind,this);this.set=j(this.set,this);this.routine=c[this.type]||i(this.type)}b.prototype.set=
function(a){var b,e,l,k;k=this.formatters;e=0;for(l=k.length;e<l;e++)b=k[e],a=d.formatters[b](a);return this.routine(this.el,a)};b.prototype.bind=function(){var a;d.adapter.subscribe(this.model,this.keypath,this.set);d.preloadData&&this.set(d.adapter.read(this.model,this.keypath));if(a=this.type,0<=o.call(h,a))return this.el.addEventListener("change",this.publish)};b.prototype.publish=function(a){return d.adapter.publish(this.model,this.keypath,n(a.target||a.srcElement))};b.prototype.unbind=function(){var a;
d.adapter.unsubscribe(this.model,this.keypath,this.set);if(a=this.type,0<=o.call(h,a))return this.el.removeEventListener("change",this.publish)};return b}();g=function(){function b(a,b){this.el=a;this.models=b;this.bind=j(this.bind,this);this.build=j(this.build,this);this.bindingRegExp=j(this.bindingRegExp,this);this.build()}b.prototype.bindingRegExp=function(){var a;return(a=d.prefix)?RegExp("^data-"+a+"-"):/^data-/};b.prototype.build=function(){var a,b,e,l,k,d,f,j,c,g,i,h;this.bindings=[];b=this.bindingRegExp();
i=this.el.getElementsByTagName("*");h=[];c=0;for(g=i.length;c<g;c++)k=i[c],h.push(function(){var c,i,h,g;h=k.attributes;g=[];c=0;for(i=h.length;c<i;c++)a=h[c],b.test(a.name)?(j=a.name.replace(b,""),f=a.value.split("|").map(function(a){return a.trim()}),d=f.shift().split("."),l=this.models[d.shift()],e=d.join("."),g.push(this.bindings.push(new m(k,j,l,e,f)))):g.push(void 0);return g}.call(this));return h};b.prototype.bind=function(){var a,b,e,c,d;c=this.bindings;d=[];b=0;for(e=c.length;b<e;b++)a=c[b],
d.push(a.bind());return d};return b}();n=function(b){switch(b.type){case "text":case "textarea":case "password":case "select-one":return b.value;case "checkbox":case "radio":return b.checked}};i=function(b){return function(a,c){return c?a.setAttribute(b,c):a.removeAttribute(b)}};f=function(b,a){null==a&&(a=!1);return function(c,d){return i(b)(c,a===!d?b:!1)}};h=["value","checked","unchecked","selected","unselected"];c={checked:f("checked"),selected:f("selected"),disabled:f("disabled"),unchecked:f("checked",
!0),unselected:f("selected",!0),enabled:f("disabled",!0),text:function(b,a){return null!=b.innerText?b.innerText=a||"":b.textContent=a||""},html:function(b,a){return b.innerHTML=a||""},value:function(b,a){return b.value=a},show:function(b,a){return b.style.display=a?"":"none"},hide:function(b,a){return b.style.display=a?"none":""}};d={preloadData:!0};f={configure:function(b){var a,c,e;null==b&&(b={});e=[];for(a in b)c=b[a],e.push(d[a]=c);return e},register:function(b,a){return c[b]=a},bind:function(b,
a){var c;null==a&&(a={});c=new g(b,a);c.bind();return c}};"undefined"!==typeof module&&null!==module?module.exports=f:this.rivets=f}).call(this);
(function(){var p,h,c,k,r,s,l,t,u,j,v,e=function(a,b){return function(){return a.apply(b,arguments)}},x=[].indexOf||function(a){for(var b=0,w=this.length;b<w;b++)if(b in this&&this[b]===a)return b;return-1};k=c=h=p=void 0;String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")});p=function(){function a(b,a,d,i,f,g){this.el=b;this.type=a;this.bindType=d;this.model=i;this.keypath=f;this.formatters=g!=null?g:[];this.publish=e(this.publish,this);this.bind=e(this.bind,
this);this.set=e(this.set,this);this.routine=this.bindType==="event"?t(this.type):h[this.type]||r(this.type)}a.prototype.set=function(b){var a,d,i,f;f=this.formatters;d=0;for(i=f.length;d<i;d++){a=f[d];b=c.formatters[a](b)}if(this.bindType==="event"){this.routine(this.el,b,this.currentListener);return this.currentListener=b}return this.routine(this.el,b)};a.prototype.bind=function(){c.adapter.subscribe(this.model,this.keypath,this.set);c.preloadData&&this.set(c.adapter.read(this.model,this.keypath));
if(this.bindType==="bidirectional")return l(this.el,"change",this.publish)};a.prototype.publish=function(b){return c.adapter.publish(this.model,this.keypath,u(b.target||b.srcElement))};return a}();k=function(){function a(b,a){this.el=b;this.models=a;this.bind=e(this.bind,this);this.build=e(this.build,this);this.bindingRegExp=e(this.bindingRegExp,this);if(this.el.jquery)this.el=this.el.get(0);this.build()}a.prototype.bindingRegExp=function(){var b;return(b=c.prefix)?RegExp("^data-"+b+"-"):/^data-/};
a.prototype.build=function(){var b,a,d,i,f,g,c,e,m,n,h,o,k,l,j;this.bindings=[];d=this.bindingRegExp();f=/^on-/;i=[this.el];i.concat(Array.prototype.slice.call(this.el.getElementsByTagName("*")));h=0;for(k=i.length;h<k;h++){e=i[h];j=e.attributes;o=0;for(l=j.length;o<l;o++){b=j[o];if(d.test(b.name)){a="attribute";n=b.name.replace(d,"");var q=g=m=c=void 0;g=b.value.split("|");q=[];c=0;for(m=g.length;c<m;c++){b=g[c];q.push(b.trim())}m=q;g=m.shift().split(".");c=this.models[g.shift()];g=g.join(".");if(f.test(n)){n=
n.replace(f,"");a="event"}else x.call(s,n)>=0&&(a="bidirectional");this.bindings.push(new p(e,n,a,c,g,m))}}}};a.prototype.bind=function(){var b,a,d,c,f;c=this.bindings;f=[];a=0;for(d=c.length;a<d;a++){b=c[a];f.push(b.bind())}return f};return a}();l=function(a,b,c){return window.addEventListener?a.addEventListener(b,c):a.attachEvent(b,c)};v=function(a,b,c){return window.removeEventListener?a.removeEventListener(b,c):a.detachEvent(b,c)};u=function(a){switch(a.type){case "text":case "textarea":case "password":case "select-one":return a.value;
case "checkbox":case "radio":return a.checked}};t=function(a){return function(b,c,d){c&&l(b,a,c);if(d)return v(b,a,d)}};r=function(a){return function(b,c){return c?b.setAttribute(a,c):b.removeAttribute(a)}};s=["value","checked","unchecked","selected","unselected"];h={enabled:function(a,b){return a.disabled=!b},disabled:function(a,b){return a.disabled=!!b},checked:function(a,b){return a.checked=!!b},unchecked:function(a,b){return a.checked=!b},selected:function(a,b){return a.selected=!!b},unselected:function(a,
b){return a.selected=!b},show:function(a,b){return a.style.display=b?"":"none"},hide:function(a,b){return a.style.display=b?"none":""},html:function(a,b){return a.innerHTML=b||""},value:function(a,b){return a.value=b},text:function(a,b){return a.innerText!=null?a.innerText=b||"":a.textContent=b||""}};c={preloadData:!0};j={configure:function(a){var b,e,d;a==null&&(a={});d=[];for(b in a){e=a[b];d.push(c[b]=e)}return d},register:function(a,b){return h[a]=b},bind:function(a,b){var c;b==null&&(b={});c=
new k(a,b);c.bind();return c}};"undefined"!==typeof module&&null!==module?module.exports=j:this.rivets=j}).call(this);
......
(function() {
var Rivets, attributeBinding, bidirectionals, getInputValue, rivets, stateBinding,
var Rivets, attributeBinding, bidirectionals, bindEvent, eventBinding, getInputValue, rivets, unbindEvent,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
Rivets = {};
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
}
Rivets.Binding = (function() {
function Binding(el, type, model, keypath, formatters) {
function Binding(el, type, bindType, model, keypath, formatters) {
this.el = el;
this.type = type;
this.bindType = bindType;
this.model = model;
this.keypath = keypath;
this.formatters = formatters != null ? formatters : [];
this.unbind = __bind(this.unbind, this);
this.publish = __bind(this.publish, this);
this.bind = __bind(this.bind, this);
this.set = __bind(this.set, this);
if (this.bindType === "event") {
this.routine = eventBinding(this.type);
} else {
this.routine = Rivets.routines[this.type] || attributeBinding(this.type);
}
}
Binding.prototype.set = function(value) {
var formatter, _i, _len, _ref;
......@@ -31,17 +40,21 @@
formatter = _ref[_i];
value = Rivets.config.formatters[formatter](value);
}
if (this.bindType === "event") {
this.routine(this.el, value, this.currentListener);
return this.currentListener = value;
} else {
return this.routine(this.el, value);
}
};
Binding.prototype.bind = function() {
var _ref;
Rivets.config.adapter.subscribe(this.model, this.keypath, this.set);
if (Rivets.config.preloadData) {
this.set(Rivets.config.adapter.read(this.model, this.keypath));
}
if (_ref = this.type, __indexOf.call(bidirectionals, _ref) >= 0) {
return this.el.addEventListener('change', this.publish);
if (this.bindType === "bidirectional") {
return bindEvent(this.el, 'change', this.publish);
}
};
......@@ -51,14 +64,6 @@
return Rivets.config.adapter.publish(this.model, this.keypath, getInputValue(el));
};
Binding.prototype.unbind = function() {
var _ref;
Rivets.config.adapter.unsubscribe(this.model, this.keypath, this.set);
if (_ref = this.type, __indexOf.call(bidirectionals, _ref) >= 0) {
return this.el.removeEventListener('change', this.publish);
}
};
return Binding;
})();
......@@ -74,6 +79,9 @@
this.bindingRegExp = __bind(this.bindingRegExp, this);
if (this.el.jquery) {
this.el = this.el.get(0);
}
this.build();
}
......@@ -88,9 +96,10 @@
};
View.prototype.build = function() {
var attribute, bindingRegExp, elements, keypath, model, node, path, pipes, type, _i, _j, _len, _len1, _ref;
var attribute, bindType, bindingRegExp, elements, eventRegExp, keypath, model, node, path, pipe, pipes, type, _i, _j, _len, _len1, _ref;
this.bindings = [];
bindingRegExp = this.bindingRegExp();
eventRegExp = /^on-/;
elements = [this.el];
elements.concat(Array.prototype.slice.call(this.el.getElementsByTagName('*')));
for (_i = 0, _len = elements.length; _i < _len; _i++) {
......@@ -99,14 +108,28 @@
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
attribute = _ref[_j];
if (bindingRegExp.test(attribute.name)) {
bindType = "attribute";
type = attribute.name.replace(bindingRegExp, '');
pipes = attribute.value.split('|').map(function(pipe) {
return pipe.trim();
});
pipes = (function() {
var _k, _len2, _ref1, _results;
_ref1 = attribute.value.split('|');
_results = [];
for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) {
pipe = _ref1[_k];
_results.push(pipe.trim());
}
return _results;
})();
path = pipes.shift().split('.');
model = this.models[path.shift()];
keypath = path.join('.');
this.bindings.push(new Rivets.Binding(node, type, model, keypath, pipes));
if (eventRegExp.test(type)) {
type = type.replace(eventRegExp, '');
bindType = "event";
} else if (__indexOf.call(bidirectionals, type) >= 0) {
bindType = "bidirectional";
}
this.bindings.push(new Rivets.Binding(node, type, bindType, model, keypath, pipes));
}
}
}
......@@ -127,6 +150,22 @@
})();
bindEvent = function(el, event, fn) {
if (window.addEventListener) {
return el.addEventListener(event, fn);
} else {
return el.attachEvent(event, fn);
}
};
unbindEvent = function(el, event, fn) {
if (window.removeEventListener) {
return el.removeEventListener(event, fn);
} else {
return el.detachEvent(event, fn);
}
};
getInputValue = function(el) {
switch (el.type) {
case 'text':
......@@ -140,6 +179,17 @@
}
};
eventBinding = function(event) {
return function(el, bind, unbind) {
if (bind) {
bindEvent(el, event, bind);
}
if (unbind) {
return unbindEvent(el, event, unbind);
}
};
};
attributeBinding = function(attr) {
return function(el, value) {
if (value) {
......@@ -150,44 +200,45 @@
};
};
stateBinding = function(attr, inverse) {
if (inverse == null) {
inverse = false;
}
return function(el, value) {
var binding;
binding = attributeBinding(attr);
return binding(el, inverse === !value ? attr : false);
};
};
bidirectionals = ['value', 'checked', 'unchecked', 'selected', 'unselected'];
Rivets.routines = {
checked: stateBinding('checked'),
selected: stateBinding('selected'),
disabled: stateBinding('disabled'),
unchecked: stateBinding('checked', true),
unselected: stateBinding('selected', true),
enabled: stateBinding('disabled', true),
text: function(el, value) {
if (el.innerText != null) {
return el.innerText = value || '';
} else {
return el.textContent = value || '';
}
enabled: function(el, value) {
return el.disabled = !value;
},
html: function(el, value) {
return el.innerHTML = value || '';
disabled: function(el, value) {
return el.disabled = !!value;
},
value: function(el, value) {
return el.value = value;
checked: function(el, value) {
return el.checked = !!value;
},
unchecked: function(el, value) {
return el.checked = !value;
},
selected: function(el, value) {
return el.selected = !!value;
},
unselected: function(el, value) {
return el.selected = !value;
},
show: function(el, value) {
return el.style.display = value ? '' : 'none';
},
hide: function(el, value) {
return el.style.display = value ? 'none' : '';
},
html: function(el, value) {
return el.innerHTML = value || '';
},
value: function(el, value) {
return el.value = value;
},
text: function(el, value) {
if (el.innerText != null) {
return el.innerText = value || '';
} else {
return el.textContent = value || '';
}
}
};
......
{
"name" : "rivets",
"description" : "Declarative DOM-binding facility.",
"version" : "0.1.9",
"description" : "Declarative data binding facility.",
"version" : "0.1.12",
"author" : "Michael Richards",
"main" : "./lib/rivets.js",
"licenses" : [{
......@@ -11,5 +11,8 @@
"repository" : {
"type" : "git",
"url" : "https://github.com/mikeric/rivets.git"
},
"scripts" : {
"build" : "coffee -o lib -c src"
}
}
......
# rivets.js
# version : 0.1.9
# version : 0.1.12
# author : Michael Richards
# license : MIT
# The Rivets namespace.
Rivets = {}
# Polyfill For String::trim.
unless String::trim then String::trim = -> @replace /^\s+|\s+$/g, ""
# A single binding between a model attribute and a DOM element.
class Rivets.Binding
# All information about the binding is passed into the constructor; the DOM
# element, the routine identifier, the model object and the keypath at which
# to listen for changes.
constructor: (@el, @type, @model, @keypath, @formatters = []) ->
constructor: (@el, @type, @bindType, @model, @keypath, @formatters = []) ->
if @bindType is "event"
@routine = eventBinding @type
else
@routine = Rivets.routines[@type] || attributeBinding @type
# Sets the value for the binding. This Basically just runs the binding routine
......@@ -20,6 +26,10 @@ class Rivets.Binding
for formatter in @formatters
value = Rivets.config.formatters[formatter] value
if @bindType is "event"
@routine @el, value, @currentListener
@currentListener = value
else
@routine @el, value
# Subscribes to the model for changes at the specified keypath. Bi-directional
......@@ -31,25 +41,20 @@ class Rivets.Binding
if Rivets.config.preloadData
@set Rivets.config.adapter.read @model, @keypath
if @type in bidirectionals
@el.addEventListener 'change', @publish
if @bindType is "bidirectional"
bindEvent @el, 'change', @publish
# Publishes the value currently set on the input element back to the model.
publish: (e) =>
el = e.target or e.srcElement
Rivets.config.adapter.publish @model, @keypath, getInputValue el
# Unsubscribes from the model and the element
unbind: =>
Rivets.config.adapter.unsubscribe @model, @keypath, @set
if @type in bidirectionals
@el.removeEventListener 'change', @publish
# A collection of bindings for a parent element.
class Rivets.View
# The parent DOM element and the model objects for binding are passed into the
# constructor.
constructor: (@el, @models) ->
@el = @el.get(0) if @el.jquery
@build()
# Regular expression used to match binding attributes.
......@@ -61,19 +66,26 @@ class Rivets.View
build: =>
@bindings = []
bindingRegExp = @bindingRegExp()
eventRegExp = /^on-/
elements = [@el]
elements.concat Array::slice.call @el.getElementsByTagName '*'
for node in elements
for attribute in node.attributes
if bindingRegExp.test attribute.name
bindType = "attribute"
type = attribute.name.replace bindingRegExp, ''
pipes = attribute.value.split('|').map (pipe) -> pipe.trim()
pipes = (pipe.trim() for pipe in attribute.value.split '|')
path = pipes.shift().split '.'
model = @models[path.shift()]
keypath = path.join '.'
@bindings.push new Rivets.Binding node, type, model, keypath, pipes
if eventRegExp.test type
type = type.replace eventRegExp, ''
bindType = "event"
else if type in bidirectionals
bindType = "bidirectional"
@bindings.push new Rivets.Binding node, type, bindType, model, keypath, pipes
# To avoid returning the result of the loop
return
......@@ -82,55 +94,70 @@ class Rivets.View
bind: =>
binding.bind() for binding in @bindings
# Cross-browser event binding
bindEvent = (el, event, fn) ->
# Check to see if addEventListener is available.
if window.addEventListener
el.addEventListener event, fn
else
# Assume we are in IE and use attachEvent.
el.attachEvent event, fn
unbindEvent = (el, event, fn) ->
# Check to see if addEventListener is available.
if window.removeEventListener
el.removeEventListener event, fn
else
# Assume we are in IE and use attachEvent.
el.detachEvent event, fn
# Returns the current input value for the specified element.
getInputValue = (el) ->
switch el.type
when 'text', 'textarea', 'password', 'select-one' then el.value
when 'checkbox', 'radio' then el.checked
# Returns an element binding routine for the specified attribute.
eventBinding = (event) -> (el, bind, unbind) ->
bindEvent el, event, bind if bind
unbindEvent el, event, unbind if unbind
# Returns an attribute binding routine for the specified attribute. This is what
# `registerBinding` falls back to when there is no routine for the binding type.
attributeBinding = (attr) -> (el, value) ->
if value then el.setAttribute attr, value else el.removeAttribute attr
# Returns a state binding routine for the specified attribute. Can optionally be
# negatively evaluated. This is used to build a lot of the core state binding
# routines.
stateBinding = (attr, inverse = false) -> (el, value) ->
binding = attributeBinding(attr)
binding el, if inverse is !value then attr else false
# Bindings that should also be observed for changes on the DOM element in order
# to propagate those changes back to the model object.
bidirectionals = ['value', 'checked', 'unchecked', 'selected', 'unselected']
# Core binding routines.
Rivets.routines =
checked:
stateBinding 'checked'
selected:
stateBinding 'selected'
disabled:
stateBinding 'disabled'
unchecked:
stateBinding 'checked', true
unselected:
stateBinding 'selected', true
enabled:
stateBinding 'disabled', true
enabled: (el, value) ->
el.disabled = !value
disabled: (el, value) ->
el.disabled = !!value
checked: (el, value) ->
el.checked = !!value
unchecked: (el, value) ->
el.checked = !value
selected: (el, value) ->
el.selected = !!value
unselected: (el, value) ->
el.selected = !value
show: (el, value) ->
el.style.display = if value then '' else 'none'
hide: (el, value) ->
el.style.display = if value then 'none' else ''
html: (el, value) ->
el.innerHTML = value or ''
value: (el, value) ->
el.value = value
text: (el, value) ->
if el.innerText?
el.innerText = value or ''
else
el.textContent = value or ''
html: (el, value) ->
el.innerHTML = value or ''
value: (el, value) ->
el.value = value
show: (el, value) ->
el.style.display = if value then '' else 'none'
hide: (el, value) ->
el.style.display = if value then 'none' else ''
# Default configuration.
Rivets.config =
......