First commit

This commit is contained in:
Theodotos Andreou 2018-01-14 13:10:16 +00:00
commit c6e2478c40
13918 changed files with 2303184 additions and 0 deletions

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,233 @@
/*! backbone.collectionsubset - v0.1.2 - 2012-12-20
* https://github.com/anthonyshort/backbone.collectionsubset
* Copyright (c) 2012 Anthony Short; Licensed MIT */
// Patched for civicrm by colemanw - added global import of _ variable
(function(_) {
Backbone.CollectionSubset = (function() {
CollectionSubset.extend = Backbone.Model.extend;
_.extend(CollectionSubset.prototype, Backbone.Events);
function CollectionSubset(options) {
if (options == null) {
options = {};
}
options = _.defaults(options, {
refresh: true,
triggers: null,
filter: function() {
return true;
},
name: null,
child: null,
parent: null
});
this.triggers = options.triggers ? options.triggers.split(' ') : [];
if (!options.child) {
options.child = new options.parent.constructor;
}
this.setParent(options.parent);
this.setChild(options.child);
this.setFilter(options.filter);
if (options.model) {
this.child.model = options.model;
}
if (options.refresh) {
this.refresh();
}
this.name = options.name;
}
CollectionSubset.prototype.setParent = function(collection) {
var _ref,
_this = this;
if ((_ref = this.parent) != null) {
_ref.off(null, null, this);
}
this.parent = collection;
this.parent.on('add', this._onParentAdd, this);
this.parent.on('remove', this._onParentRemove, this);
this.parent.on('reset', this._onParentReset, this);
this.parent.on('change', this._onParentChange, this);
this.parent.on('dispose', this.dispose, this);
this.parent.on('loading', (function() {
return _this.child.trigger('loading');
}), this);
return this.parent.on('ready', (function() {
return _this.child.trigger('ready');
}), this);
};
CollectionSubset.prototype.setChild = function(collection) {
var _ref;
if ((_ref = this.child) != null) {
_ref.off(null, null, this);
}
this.child = collection;
this.child.on('add', this._onChildAdd, this);
this.child.on('reset', this._onChildReset, this);
this.child.on('dispose', this.dispose, this);
this.child.superset = this.parent;
this.child.filterer = this;
this.child.url = this.parent.url;
return this.child.model = this.parent.model;
};
CollectionSubset.prototype.setFilter = function(fn) {
var filter;
filter = function(model) {
var matchesFilter, matchesParentFilter;
matchesFilter = fn.call(this, model);
matchesParentFilter = this.parent.filterer ? this.parent.filterer.filter(model) : true;
return matchesFilter && matchesParentFilter;
};
return this.filter = _.bind(filter, this);
};
CollectionSubset.prototype.refresh = function(options) {
var models;
if (options == null) {
options = {};
}
models = this.parent.filter(this.filter);
this.child.reset(models, {
subset: this
});
return this.child.trigger('refresh');
};
CollectionSubset.prototype._replaceChildModel = function(parentModel) {
var childModel, index;
childModel = this._getByCid(this.child, parentModel.cid);
if (childModel === parentModel) {
return;
}
if (_.isUndefined(childModel)) {
return this.child.add(parentModel, {
subset: this
});
} else {
index = this.child.indexOf(childModel);
this.child.remove(childModel);
return this.child.add(parentModel, {
at: index,
subset: this
});
}
};
CollectionSubset.prototype._onParentAdd = function(model, collection, options) {
if (options && options.subset === this) {
return;
}
if (this.filter(model)) {
return this._replaceChildModel(model);
}
};
CollectionSubset.prototype._onParentRemove = function(model, collection, options) {
return this.child.remove(model, options);
};
CollectionSubset.prototype._onParentReset = function(collection, options) {
return this.refresh();
};
CollectionSubset.prototype._onParentChange = function(model, changes) {
if (!this.triggerMatched(model)) {
return;
}
if (this.filter(model)) {
return this.child.add(model);
} else {
return this.child.remove(model);
}
};
CollectionSubset.prototype._onChildAdd = function(model, collection, options) {
var parentModel;
if (options && options.subset === this) {
return;
}
this.parent.add(model);
parentModel = this._getByCid(this.parent, model.cid);
if (!parentModel) {
return;
}
if (this.filter(parentModel)) {
return this._replaceChildModel(parentModel);
} else {
return this.child.remove(model);
}
};
CollectionSubset.prototype._onChildReset = function(collection, options) {
if (options && options.subset === this) {
return;
}
this.parent.add(this.child.models);
return this.refresh();
};
CollectionSubset.prototype._getByCid = function(model, cid) {
var fn;
fn = model.getByCid || model.get;
return fn.apply(model, [cid]);
};
CollectionSubset.prototype.triggerMatched = function(model) {
var changedAttrs;
if (this.triggers.length === 0) {
return true;
}
if (!model.hasChanged()) {
return false;
}
changedAttrs = _.keys(model.changedAttributes());
return _.intersection(this.triggers, changedAttrs).length > 0;
};
CollectionSubset.prototype.dispose = function() {
var prop, _base, _i, _len, _ref;
if (this.disposed) {
return;
}
this.trigger('dispose', this);
this.parent.off(null, null, this);
this.child.off(null, null, this);
if (typeof (_base = this.child).dispose === "function") {
_base.dispose();
}
this.off();
_ref = ['parent', 'child', 'options'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
prop = _ref[_i];
delete this[prop];
}
return this.disposed = true;
};
return CollectionSubset;
})();
Backbone.Collection.prototype.subcollection = function(options) {
var subset;
if (options == null) {
options = {};
}
_.defaults(options, {
child: new this.constructor,
parent: this
});
subset = new Backbone.CollectionSubset(options);
return subset.child;
};
if (typeof module !== "undefined" && module !== null) {
module.exports = Backbone.CollectionSubset;
}
}(_));

View file

@ -0,0 +1,4 @@
/*! backbone.collectionsubset - v0.1.2 - 2012-12-20
* https://github.com/anthonyshort/backbone.collectionsubset
* Copyright (c) 2012 Anthony Short; Licensed MIT */
(function(_){Backbone.CollectionSubset=function(){function e(e){e==null&&(e={}),e=_.defaults(e,{refresh:!0,triggers:null,filter:function(){return!0},name:null,child:null,parent:null}),this.triggers=e.triggers?e.triggers.split(" "):[],e.child||(e.child=new e.parent.constructor),this.setParent(e.parent),this.setChild(e.child),this.setFilter(e.filter),e.model&&(this.child.model=e.model),e.refresh&&this.refresh(),this.name=e.name}return e.extend=Backbone.Model.extend,_.extend(e.prototype,Backbone.Events),e.prototype.setParent=function(e){var t,n=this;return(t=this.parent)!=null&&t.off(null,null,this),this.parent=e,this.parent.on("add",this._onParentAdd,this),this.parent.on("remove",this._onParentRemove,this),this.parent.on("reset",this._onParentReset,this),this.parent.on("change",this._onParentChange,this),this.parent.on("dispose",this.dispose,this),this.parent.on("loading",function(){return n.child.trigger("loading")},this),this.parent.on("ready",function(){return n.child.trigger("ready")},this)},e.prototype.setChild=function(e){var t;return(t=this.child)!=null&&t.off(null,null,this),this.child=e,this.child.on("add",this._onChildAdd,this),this.child.on("reset",this._onChildReset,this),this.child.on("dispose",this.dispose,this),this.child.superset=this.parent,this.child.filterer=this,this.child.url=this.parent.url,this.child.model=this.parent.model},e.prototype.setFilter=function(e){var t;return t=function(t){var n,r;return n=e.call(this,t),r=this.parent.filterer?this.parent.filterer.filter(t):!0,n&&r},this.filter=_.bind(t,this)},e.prototype.refresh=function(e){var t;return e==null&&(e={}),t=this.parent.filter(this.filter),this.child.reset(t,{subset:this}),this.child.trigger("refresh")},e.prototype._replaceChildModel=function(e){var t,n;t=this._getByCid(this.child,e.cid);if(t===e)return;return _.isUndefined(t)?this.child.add(e,{subset:this}):(n=this.child.indexOf(t),this.child.remove(t),this.child.add(e,{at:n,subset:this}))},e.prototype._onParentAdd=function(e,t,n){if(n&&n.subset===this)return;if(this.filter(e))return this._replaceChildModel(e)},e.prototype._onParentRemove=function(e,t,n){return this.child.remove(e,n)},e.prototype._onParentReset=function(e,t){return this.refresh()},e.prototype._onParentChange=function(e,t){if(!this.triggerMatched(e))return;return this.filter(e)?this.child.add(e):this.child.remove(e)},e.prototype._onChildAdd=function(e,t,n){var r;if(n&&n.subset===this)return;this.parent.add(e),r=this._getByCid(this.parent,e.cid);if(!r)return;return this.filter(r)?this._replaceChildModel(r):this.child.remove(e)},e.prototype._onChildReset=function(e,t){if(t&&t.subset===this)return;return this.parent.add(this.child.models),this.refresh()},e.prototype._getByCid=function(e,t){var n;return n=e.getByCid||e.get,n.apply(e,[t])},e.prototype.triggerMatched=function(e){var t;return this.triggers.length===0?!0:e.hasChanged()?(t=_.keys(e.changedAttributes()),_.intersection(this.triggers,t).length>0):!1},e.prototype.dispose=function(){var e,t,n,r,i;if(this.disposed)return;this.trigger("dispose",this),this.parent.off(null,null,this),this.child.off(null,null,this),typeof (t=this.child).dispose=="function"&&t.dispose(),this.off(),i=["parent","child","options"];for(n=0,r=i.length;n<r;n++)e=i[n],delete this[e];return this.disposed=!0},e}(),Backbone.Collection.prototype.subcollection=function(e){var t;return e==null&&(e={}),_.defaults(e,{child:new this.constructor,parent:this}),t=new Backbone.CollectionSubset(e),t.child},typeof module!="undefined"&&module!==null&&(module.exports=Backbone.CollectionSubset)}(_));

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,576 @@
// Backbone.ModelBinder v1.0.2
// (c) 2013 Bart Wood
// Distributed Under MIT License
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['underscore', 'jquery', 'backbone'], factory);
} else {
// Browser globals
factory(_, $, Backbone);
}
}(function(_, $, Backbone){
if(!Backbone){
throw 'Please include Backbone.js before Backbone.ModelBinder.js';
}
Backbone.ModelBinder = function(){
_.bindAll.apply(_, [this].concat(_.functions(this)));
};
// Static setter for class level options
Backbone.ModelBinder.SetOptions = function(options){
Backbone.ModelBinder.options = options;
};
// Current version of the library.
Backbone.ModelBinder.VERSION = '1.0.2';
Backbone.ModelBinder.Constants = {};
Backbone.ModelBinder.Constants.ModelToView = 'ModelToView';
Backbone.ModelBinder.Constants.ViewToModel = 'ViewToModel';
_.extend(Backbone.ModelBinder.prototype, {
bind:function (model, rootEl, attributeBindings, options) {
this.unbind();
this._model = model;
this._rootEl = rootEl;
this._setOptions(options);
if (!this._model) this._throwException('model must be specified');
if (!this._rootEl) this._throwException('rootEl must be specified');
if(attributeBindings){
// Create a deep clone of the attribute bindings
this._attributeBindings = $.extend(true, {}, attributeBindings);
this._initializeAttributeBindings();
this._initializeElBindings();
}
else {
this._initializeDefaultBindings();
}
this._bindModelToView();
this._bindViewToModel();
},
bindCustomTriggers: function (model, rootEl, triggers, attributeBindings, modelSetOptions) {
this._triggers = triggers;
this.bind(model, rootEl, attributeBindings, modelSetOptions)
},
unbind:function () {
this._unbindModelToView();
this._unbindViewToModel();
if(this._attributeBindings){
delete this._attributeBindings;
this._attributeBindings = undefined;
}
},
_setOptions: function(options){
this._options = _.extend({
boundAttribute: 'name'
}, Backbone.ModelBinder.options, options);
// initialize default options
if(!this._options['modelSetOptions']){
this._options['modelSetOptions'] = {};
}
this._options['modelSetOptions'].changeSource = 'ModelBinder';
if(!this._options['changeTriggers']){
this._options['changeTriggers'] = {'': 'change', '[contenteditable]': 'blur'};
}
if(!this._options['initialCopyDirection']){
this._options['initialCopyDirection'] = Backbone.ModelBinder.Constants.ModelToView;
}
},
// Converts the input bindings, which might just be empty or strings, to binding objects
_initializeAttributeBindings:function () {
var attributeBindingKey, inputBinding, attributeBinding, elementBindingCount, elementBinding;
for (attributeBindingKey in this._attributeBindings) {
inputBinding = this._attributeBindings[attributeBindingKey];
if (_.isString(inputBinding)) {
attributeBinding = {elementBindings: [{selector: inputBinding}]};
}
else if (_.isArray(inputBinding)) {
attributeBinding = {elementBindings: inputBinding};
}
else if(_.isObject(inputBinding)){
attributeBinding = {elementBindings: [inputBinding]};
}
else {
this._throwException('Unsupported type passed to Model Binder ' + attributeBinding);
}
// Add a linkage from the element binding back to the attribute binding
for(elementBindingCount = 0; elementBindingCount < attributeBinding.elementBindings.length; elementBindingCount++){
elementBinding = attributeBinding.elementBindings[elementBindingCount];
elementBinding.attributeBinding = attributeBinding;
}
attributeBinding.attributeName = attributeBindingKey;
this._attributeBindings[attributeBindingKey] = attributeBinding;
}
},
// If the bindings are not specified, the default binding is performed on the specified attribute, name by default
_initializeDefaultBindings: function(){
var elCount, elsWithAttribute, matchedEl, name, attributeBinding;
this._attributeBindings = {};
elsWithAttribute = $('[' + this._options['boundAttribute'] + ']', this._rootEl);
for(elCount = 0; elCount < elsWithAttribute.length; elCount++){
matchedEl = elsWithAttribute[elCount];
name = $(matchedEl).attr(this._options['boundAttribute']);
// For elements like radio buttons we only want a single attribute binding with possibly multiple element bindings
if(!this._attributeBindings[name]){
attributeBinding = {attributeName: name};
attributeBinding.elementBindings = [{attributeBinding: attributeBinding, boundEls: [matchedEl]}];
this._attributeBindings[name] = attributeBinding;
}
else{
this._attributeBindings[name].elementBindings.push({attributeBinding: this._attributeBindings[name], boundEls: [matchedEl]});
}
}
},
_initializeElBindings:function () {
var bindingKey, attributeBinding, bindingCount, elementBinding, foundEls, elCount, el;
for (bindingKey in this._attributeBindings) {
attributeBinding = this._attributeBindings[bindingKey];
for (bindingCount = 0; bindingCount < attributeBinding.elementBindings.length; bindingCount++) {
elementBinding = attributeBinding.elementBindings[bindingCount];
if (elementBinding.selector === '') {
foundEls = $(this._rootEl);
}
else {
foundEls = $(elementBinding.selector, this._rootEl);
}
if (foundEls.length === 0) {
this._throwException('Bad binding found. No elements returned for binding selector ' + elementBinding.selector);
}
else {
elementBinding.boundEls = [];
for (elCount = 0; elCount < foundEls.length; elCount++) {
el = foundEls[elCount];
elementBinding.boundEls.push(el);
}
}
}
}
},
_bindModelToView: function () {
this._model.on('change', this._onModelChange, this);
if(this._options['initialCopyDirection'] === Backbone.ModelBinder.Constants.ModelToView){
this.copyModelAttributesToView();
}
},
// attributesToCopy is an optional parameter - if empty, all attributes
// that are bound will be copied. Otherwise, only attributeBindings specified
// in the attributesToCopy are copied.
copyModelAttributesToView: function(attributesToCopy){
var attributeName, attributeBinding;
for (attributeName in this._attributeBindings) {
if(attributesToCopy === undefined || _.indexOf(attributesToCopy, attributeName) !== -1){
attributeBinding = this._attributeBindings[attributeName];
this._copyModelToView(attributeBinding);
}
}
},
copyViewValuesToModel: function(){
var bindingKey, attributeBinding, bindingCount, elementBinding, elCount, el;
for (bindingKey in this._attributeBindings) {
attributeBinding = this._attributeBindings[bindingKey];
for (bindingCount = 0; bindingCount < attributeBinding.elementBindings.length; bindingCount++) {
elementBinding = attributeBinding.elementBindings[bindingCount];
if(this._isBindingUserEditable(elementBinding)){
if(this._isBindingRadioGroup(elementBinding)){
el = this._getRadioButtonGroupCheckedEl(elementBinding);
if(el){
this._copyViewToModel(elementBinding, el);
}
}
else {
for(elCount = 0; elCount < elementBinding.boundEls.length; elCount++){
el = $(elementBinding.boundEls[elCount]);
if(this._isElUserEditable(el)){
this._copyViewToModel(elementBinding, el);
}
}
}
}
}
}
},
_unbindModelToView: function(){
if(this._model){
this._model.off('change', this._onModelChange);
this._model = undefined;
}
},
_bindViewToModel: function () {
_.each(this._options['changeTriggers'], function (event, selector) {
$(this._rootEl).delegate(selector, event, this._onElChanged);
}, this);
if(this._options['initialCopyDirection'] === Backbone.ModelBinder.Constants.ViewToModel){
this.copyViewValuesToModel();
}
},
_unbindViewToModel: function () {
if(this._options && this._options['changeTriggers']){
_.each(this._options['changeTriggers'], function (event, selector) {
$(this._rootEl).undelegate(selector, event, this._onElChanged);
}, this);
}
},
_onElChanged:function (event) {
var el, elBindings, elBindingCount, elBinding;
el = $(event.target)[0];
elBindings = this._getElBindings(el);
for(elBindingCount = 0; elBindingCount < elBindings.length; elBindingCount++){
elBinding = elBindings[elBindingCount];
if (this._isBindingUserEditable(elBinding)) {
this._copyViewToModel(elBinding, el);
}
}
},
_isBindingUserEditable: function(elBinding){
return elBinding.elAttribute === undefined ||
elBinding.elAttribute === 'text' ||
elBinding.elAttribute === 'html';
},
_isElUserEditable: function(el){
var isContentEditable = el.attr('contenteditable');
return isContentEditable || el.is('input') || el.is('select') || el.is('textarea');
},
_isBindingRadioGroup: function(elBinding){
var elCount, el;
var isAllRadioButtons = elBinding.boundEls.length > 0;
for(elCount = 0; elCount < elBinding.boundEls.length; elCount++){
el = $(elBinding.boundEls[elCount]);
if(el.attr('type') !== 'radio'){
isAllRadioButtons = false;
break;
}
}
return isAllRadioButtons;
},
_getRadioButtonGroupCheckedEl: function(elBinding){
var elCount, el;
for(elCount = 0; elCount < elBinding.boundEls.length; elCount++){
el = $(elBinding.boundEls[elCount]);
if(el.attr('type') === 'radio' && el.attr('checked')){
return el;
}
}
return undefined;
},
_getElBindings:function (findEl) {
var attributeName, attributeBinding, elementBindingCount, elementBinding, boundElCount, boundEl;
var elBindings = [];
for (attributeName in this._attributeBindings) {
attributeBinding = this._attributeBindings[attributeName];
for (elementBindingCount = 0; elementBindingCount < attributeBinding.elementBindings.length; elementBindingCount++) {
elementBinding = attributeBinding.elementBindings[elementBindingCount];
for (boundElCount = 0; boundElCount < elementBinding.boundEls.length; boundElCount++) {
boundEl = elementBinding.boundEls[boundElCount];
if (boundEl === findEl) {
elBindings.push(elementBinding);
}
}
}
}
return elBindings;
},
_onModelChange:function () {
var changedAttribute, attributeBinding;
for (changedAttribute in this._model.changedAttributes()) {
attributeBinding = this._attributeBindings[changedAttribute];
if (attributeBinding) {
this._copyModelToView(attributeBinding);
}
}
},
_copyModelToView:function (attributeBinding) {
var elementBindingCount, elementBinding, boundElCount, boundEl, value, convertedValue;
value = this._model.get(attributeBinding.attributeName);
for (elementBindingCount = 0; elementBindingCount < attributeBinding.elementBindings.length; elementBindingCount++) {
elementBinding = attributeBinding.elementBindings[elementBindingCount];
for (boundElCount = 0; boundElCount < elementBinding.boundEls.length; boundElCount++) {
boundEl = elementBinding.boundEls[boundElCount];
if(!boundEl._isSetting){
convertedValue = this._getConvertedValue(Backbone.ModelBinder.Constants.ModelToView, elementBinding, value);
this._setEl($(boundEl), elementBinding, convertedValue);
}
}
}
},
_setEl: function (el, elementBinding, convertedValue) {
if (elementBinding.elAttribute) {
this._setElAttribute(el, elementBinding, convertedValue);
}
else {
this._setElValue(el, convertedValue);
}
},
_setElAttribute:function (el, elementBinding, convertedValue) {
switch (elementBinding.elAttribute) {
case 'html':
el.html(convertedValue);
break;
case 'text':
el.text(convertedValue);
break;
case 'enabled':
el.prop('disabled', !convertedValue);
break;
case 'displayed':
el[convertedValue ? 'show' : 'hide']();
break;
case 'hidden':
el[convertedValue ? 'hide' : 'show']();
break;
case 'css':
el.css(elementBinding.cssAttribute, convertedValue);
break;
case 'class':
var previousValue = this._model.previous(elementBinding.attributeBinding.attributeName);
var currentValue = this._model.get(elementBinding.attributeBinding.attributeName);
// is current value is now defined then remove the class the may have been set for the undefined value
if(!_.isUndefined(previousValue) || !_.isUndefined(currentValue)){
previousValue = this._getConvertedValue(Backbone.ModelBinder.Constants.ModelToView, elementBinding, previousValue);
el.removeClass(previousValue);
}
if(convertedValue){
el.addClass(convertedValue);
}
break;
default:
el.attr(elementBinding.elAttribute, convertedValue);
}
},
_setElValue:function (el, convertedValue) {
if(el.attr('type')){
switch (el.attr('type')) {
case 'radio':
if (el.val() === convertedValue) {
// must defer the change trigger or the change will actually fire with the old value
el.prop('checked') || _.defer(function() { el.trigger('change'); });
el.prop('checked', true);
}
else {
// must defer the change trigger or the change will actually fire with the old value
el.prop('checked', false);
}
break;
case 'checkbox':
// must defer the change trigger or the change will actually fire with the old value
el.prop('checked') === !!convertedValue || _.defer(function() { el.trigger('change') });
el.prop('checked', !!convertedValue);
break;
case 'file':
break;
default:
el.val(convertedValue);
}
}
else if(el.is('input') || el.is('select') || el.is('textarea')){
el.val(convertedValue || (convertedValue === 0 ? '0' : ''));
}
else {
el.text(convertedValue || (convertedValue === 0 ? '0' : ''));
}
},
_copyViewToModel: function (elementBinding, el) {
var result, value, convertedValue;
if (!el._isSetting) {
el._isSetting = true;
result = this._setModel(elementBinding, $(el));
el._isSetting = false;
if(result && elementBinding.converter){
value = this._model.get(elementBinding.attributeBinding.attributeName);
convertedValue = this._getConvertedValue(Backbone.ModelBinder.Constants.ModelToView, elementBinding, value);
this._setEl($(el), elementBinding, convertedValue);
}
}
},
_getElValue: function(elementBinding, el){
switch (el.attr('type')) {
case 'checkbox':
return el.prop('checked') ? true : false;
default:
if(el.attr('contenteditable') !== undefined){
return el.html();
}
else {
return el.val();
}
}
},
_setModel: function (elementBinding, el) {
var data = {};
var elVal = this._getElValue(elementBinding, el);
elVal = this._getConvertedValue(Backbone.ModelBinder.Constants.ViewToModel, elementBinding, elVal);
data[elementBinding.attributeBinding.attributeName] = elVal;
return this._model.set(data, this._options['modelSetOptions']);
},
_getConvertedValue: function (direction, elementBinding, value) {
if (elementBinding.converter) {
value = elementBinding.converter(direction, value, elementBinding.attributeBinding.attributeName, this._model, elementBinding.boundEls);
}
return value;
},
_throwException: function(message){
if(this._options.suppressThrows){
if(console && console.error){
console.error(message);
}
}
else {
throw message;
}
}
});
Backbone.ModelBinder.CollectionConverter = function(collection){
this._collection = collection;
if(!this._collection){
throw 'Collection must be defined';
}
_.bindAll(this, 'convert');
};
_.extend(Backbone.ModelBinder.CollectionConverter.prototype, {
convert: function(direction, value){
if (direction === Backbone.ModelBinder.Constants.ModelToView) {
return value ? value.id : undefined;
}
else {
return this._collection.get(value);
}
}
});
// A static helper function to create a default set of bindings that you can customize before calling the bind() function
// rootEl - where to find all of the bound elements
// attributeType - probably 'name' or 'id' in most cases
// converter(optional) - the default converter you want applied to all your bindings
// elAttribute(optional) - the default elAttribute you want applied to all your bindings
Backbone.ModelBinder.createDefaultBindings = function(rootEl, attributeType, converter, elAttribute){
var foundEls, elCount, foundEl, attributeName;
var bindings = {};
foundEls = $('[' + attributeType + ']', rootEl);
for(elCount = 0; elCount < foundEls.length; elCount++){
foundEl = foundEls[elCount];
attributeName = $(foundEl).attr(attributeType);
if(!bindings[attributeName]){
var attributeBinding = {selector: '[' + attributeType + '="' + attributeName + '"]'};
bindings[attributeName] = attributeBinding;
if(converter){
bindings[attributeName].converter = converter;
}
if(elAttribute){
bindings[attributeName].elAttribute = elAttribute;
}
}
}
return bindings;
};
// Helps you to combine 2 sets of bindings
Backbone.ModelBinder.combineBindings = function(destination, source){
_.each(source, function(value, key){
var elementBinding = {selector: value.selector};
if(value.converter){
elementBinding.converter = value.converter;
}
if(value.elAttribute){
elementBinding.elAttribute = value.elAttribute;
}
if(!destination[key]){
destination[key] = elementBinding;
}
else {
destination[key] = [destination[key], elementBinding];
}
});
return destination;
};
return Backbone.ModelBinder;
}));

View file

@ -0,0 +1,486 @@
/*
json2.js
2012-10-08
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or '&nbsp;'),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());