Skip to content

Instantly share code, notes, and snippets.

@felixlaumon
Created July 17, 2013 11:35
Show Gist options
  • Save felixlaumon/6019727 to your computer and use it in GitHub Desktop.
Save felixlaumon/6019727 to your computer and use it in GitHub Desktop.
Rivets.js each=* binder in JavaScript
rivets.binders['each-*'] = {
block: true,
bind: function (el) {
var attr = ['data', this.view.config.prefix, this.type]
.join('-')
.replace('--', '-');
var declaration = el.getAttribute(attr);
var comment = ' rivets: ' + this.type + ' ';
this.iterated = [];
this.marker = document.createComment(comment);
el.removeAttribute(attr);
el.parentNode.insertBefore(this.marker, el);
el.parentNode.removeChild(el);
},
unbind: function () {
if (!this.iterated || !this.iterated.length) {
return;
}
_.each(this.iterated, function (view) {
view.unbind();
});
},
routine: function (el, collection) {
var _this = this;
var modelName = this.args[0];
collection = collection || [];
if (this.iterated.length > collection.length) {
_.times(this.iterated.length - collection.length, function () {
var view = _this.iterated.pop();
view.unbind();
_this.marker.parentNode.removeChild(view.els[0]);
});
}
_.each(collection, function (model, i) {
var previous;
var options;
var data = {};
data[modelName] = model;
if (!_this.iterated[i]) {
// Append new model at the end
_.each(_this.models, function (model, key) {
if (model) {
data[key] = model;
}
});
if (_this.iterated.length) {
previous = _this.iterated[_this.iterated.length - 1].els[0];
} else {
previous = _this.marker;
}
options = {
binders: _this.view.options.binders,
formatters: _this.view.options.formatters,
config: {}
}
_.extend(options.config, _this.view.options.config);
options.config.preloadData = true;
var template = el.cloneNode(true);
var view = new rivets._.View(template, data, options);
view.bind();
_this.iterated.push(view);
_this.marker.parentNode.insertBefore(template, previous.nextSibling);
} else if (_this.iterated[i].models[modelName] !== model) {
// If the model is updated with another reference
console.log('update model', data);
_this.iterated[i].update(data);
}
});
},
update: function (models) {
var modelName = this.args[0];
var data = {};
_.forIn(models, function (model, key) {
if (key !== modelName) {
data[key] = model;
}
});
_.each(this.iterated, function (view) {
view.update(data);
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment