Rivets.js component example
by alexchetv
HTML
<script src="https://rawgit.com/mikeric/rivets/master/dist/rivets.bundled.min.js"></script>
<div id="view">
<div>
<!-- THE COMPONENT NEEDS TO BE INSIDE A SEPARATE ELEMENT OR ELSE
THE P TAG BELOW GETS REMOVED -->
<counter counter-attr="modelCounter" color-attr="modelColor"/>
</div>
<p rv-style="modelColor.value | toColorStyle">{modelCounter.value}</p>
</div>
JavaScript
var model = {
modelCounter: {
value: 10
},
modelColor: {
value: 'red'
}
};
rivets.formatters.toColorStyle = function(v) {
return 'color: ' + v;
};
function counterViewModel(attributes) {
this.data = attributes;
this.increment = function (event, scope) {
// Rivets renames kebab-case to camelCase
scope.data.counterAttr.value++;
};
this.decrement = function (event, scope) {
scope.data.counterAttr.value--;
};
this.toggleColor = function (event, scope) {
var old = scope.data.colorAttr.value;
if (old === 'red') scope.data.colorAttr.value = 'blue';
else scope.data.colorAttr.value = 'red';
};
}
rivets.components['counter'] = {
template: function() {
return '<button rv-on-click="increment">+</button>' +
'<button rv-on-click="decrement">-</button>' +
'<button rv-on-click="toggleColor">toggle color</button>';
},
initialize: function(el, attributes) {
return new counterViewModel(attributes);
}
};
rivets.bind(document.querySelector('#view'), model);