sonarr-repo-only/UI/JsLibraries/backbone.modelbinder.js

576 lines
22 KiB
JavaScript
Raw Normal View History

// Backbone.ModelBinder v1.0.2
// (c) 2013 Bart Wood
2013-01-23 05:58:17 +00:00
// 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){
2013-01-23 05:58:17 +00:00
if(!Backbone){
2013-01-23 05:58:17 +00:00
throw 'Please include Backbone.js before Backbone.ModelBinder.js';
}
Backbone.ModelBinder = function(){
2013-01-23 05:58:17 +00:00
_.bindAll(this);
};
// Static setter for class level options
Backbone.ModelBinder.SetOptions = function(options){
Backbone.ModelBinder.options = options;
2013-01-23 05:58:17 +00:00
};
// Current version of the library.
Backbone.ModelBinder.VERSION = '1.0.2';
2013-01-23 05:58:17 +00:00
Backbone.ModelBinder.Constants = {};
Backbone.ModelBinder.Constants.ModelToView = 'ModelToView';
Backbone.ModelBinder.Constants.ViewToModel = 'ViewToModel';
_.extend(Backbone.ModelBinder.prototype, {
bind:function (model, rootEl, attributeBindings, options) {
2013-01-23 05:58:17 +00:00
this.unbind();
this._model = model;
this._rootEl = rootEl;
this._setOptions(options);
2013-01-23 05:58:17 +00:00
if (!this._model) this._throwException('model must be specified');
if (!this._rootEl) this._throwException('rootEl must be specified');
2013-01-23 05:58:17 +00:00
if(attributeBindings){
2013-01-23 05:58:17 +00:00
// 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)
},
2013-01-23 05:58:17 +00:00
unbind:function () {
2013-01-23 05:58:17 +00:00
this._unbindModelToView();
this._unbindViewToModel();
if(this._attributeBindings){
2013-01-23 05:58:17 +00:00
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;
}
},
2013-01-23 05:58:17 +00:00
// Converts the input bindings, which might just be empty or strings, to binding objects
_initializeAttributeBindings:function () {
2013-01-23 05:58:17 +00:00
var attributeBindingKey, inputBinding, attributeBinding, elementBindingCount, elementBinding;
for (attributeBindingKey in this._attributeBindings) {
inputBinding = this._attributeBindings[attributeBindingKey];
if (_.isString(inputBinding)) {
attributeBinding = {elementBindings: [{selector: inputBinding}]};
2013-01-23 05:58:17 +00:00
}
else if (_.isArray(inputBinding)) {
attributeBinding = {elementBindings: inputBinding};
2013-01-23 05:58:17 +00:00
}
else if(_.isObject(inputBinding)){
attributeBinding = {elementBindings: [inputBinding]};
2013-01-23 05:58:17 +00:00
}
else {
this._throwException('Unsupported type passed to Model Binder ' + attributeBinding);
2013-01-23 05:58:17 +00:00
}
// Add a linkage from the element binding back to the attribute binding
for(elementBindingCount = 0; elementBindingCount < attributeBinding.elementBindings.length; elementBindingCount++){
2013-01-23 05:58:17 +00:00
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;
2013-01-23 05:58:17 +00:00
this._attributeBindings = {};
elsWithAttribute = $('[' + this._options['boundAttribute'] + ']', this._rootEl);
2013-01-23 05:58:17 +00:00
for(elCount = 0; elCount < elsWithAttribute.length; elCount++){
matchedEl = elsWithAttribute[elCount];
name = $(matchedEl).attr(this._options['boundAttribute']);
2013-01-23 05:58:17 +00:00
// 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]}];
2013-01-23 05:58:17 +00:00
this._attributeBindings[name] = attributeBinding;
}
else{
this._attributeBindings[name].elementBindings.push({attributeBinding: this._attributeBindings[name], boundEls: [matchedEl]});
2013-01-23 05:58:17 +00:00
}
}
},
_initializeElBindings:function () {
2013-01-23 05:58:17 +00:00
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);
2013-01-23 05:58:17 +00:00
}
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();
}
2013-01-23 05:58:17 +00:00
},
// 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){
2013-01-23 05:58:17 +00:00
var attributeName, attributeBinding;
for (attributeName in this._attributeBindings) {
if(attributesToCopy === undefined || _.indexOf(attributesToCopy, attributeName) !== -1){
2013-01-23 05:58:17 +00:00
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){
2013-01-23 05:58:17 +00:00
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();
2013-01-23 05:58:17 +00:00
}
},
_unbindViewToModel: function () {
if(this._options && this._options['changeTriggers']){
_.each(this._options['changeTriggers'], function (event, selector) {
$(this._rootEl).undelegate(selector, event, this._onElChanged);
}, this);
2013-01-23 05:58:17 +00:00
}
},
_onElChanged:function (event) {
2013-01-23 05:58:17 +00:00
var el, elBindings, elBindingCount, elBinding;
el = $(event.target)[0];
elBindings = this._getElBindings(el);
for(elBindingCount = 0; elBindingCount < elBindings.length; elBindingCount++){
2013-01-23 05:58:17 +00:00
elBinding = elBindings[elBindingCount];
if (this._isBindingUserEditable(elBinding)) {
this._copyViewToModel(elBinding, el);
}
}
},
_isBindingUserEditable: function(elBinding){
2013-01-23 05:58:17 +00:00
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) {
2013-01-23 05:58:17 +00:00
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 () {
2013-01-23 05:58:17 +00:00
var changedAttribute, attributeBinding;
for (changedAttribute in this._model.changedAttributes()) {
attributeBinding = this._attributeBindings[changedAttribute];
if (attributeBinding) {
this._copyModelToView(attributeBinding);
}
}
},
_copyModelToView:function (attributeBinding) {
2013-01-23 05:58:17 +00:00
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){
2013-01-23 05:58:17 +00:00
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) {
2013-01-23 05:58:17 +00:00
switch (elementBinding.elAttribute) {
case 'html':
el.html(convertedValue);
break;
case 'text':
el.text(convertedValue);
break;
case 'enabled':
el.prop('disabled', !convertedValue);
2013-01-23 05:58:17 +00:00
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)){
2013-01-23 05:58:17 +00:00
previousValue = this._getConvertedValue(Backbone.ModelBinder.Constants.ModelToView, elementBinding, previousValue);
el.removeClass(previousValue);
}
if(convertedValue){
2013-01-23 05:58:17 +00:00
el.addClass(convertedValue);
}
break;
default:
el.attr(elementBinding.elAttribute, convertedValue);
}
},
_setElValue:function (el, convertedValue) {
if(el.attr('type')){
2013-01-23 05:58:17 +00:00
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);
2013-01-23 05:58:17 +00:00
}
else {
// must defer the change trigger or the change will actually fire with the old value
el.prop('checked', false);
}
2013-01-23 05:58:17 +00:00
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);
2013-01-23 05:58:17 +00:00
break;
case 'file':
break;
2013-01-23 05:58:17 +00:00
default:
el.val(convertedValue);
}
}
else if(el.is('input') || el.is('select') || el.is('textarea')){
el.val(convertedValue || (convertedValue === 0 ? '0' : ''));
2013-01-23 05:58:17 +00:00
}
else {
el.text(convertedValue || (convertedValue === 0 ? '0' : ''));
2013-01-23 05:58:17 +00:00
}
},
_copyViewToModel: function (elementBinding, el) {
var result, value, convertedValue;
2013-01-23 05:58:17 +00:00
if (!el._isSetting) {
el._isSetting = true;
result = this._setModel(elementBinding, $(el));
2013-01-23 05:58:17 +00:00
el._isSetting = false;
if(result && elementBinding.converter){
2013-01-23 05:58:17 +00:00
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){
2013-01-23 05:58:17 +00:00
switch (el.attr('type')) {
case 'checkbox':
return el.prop('checked') ? true : false;
default:
if(el.attr('contenteditable') !== undefined){
2013-01-23 05:58:17 +00:00
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']);
2013-01-23 05:58:17 +00:00
},
_getConvertedValue: function (direction, elementBinding, value) {
if (elementBinding.converter) {
value = elementBinding.converter(direction, value, elementBinding.attributeBinding.attributeName, this._model, elementBinding.boundEls);
2013-01-23 05:58:17 +00:00
}
return value;
},
_throwException: function(message){
if(this._options.suppressThrows){
if(console && console.error){
console.error(message);
}
}
else {
throw message;
}
2013-01-23 05:58:17 +00:00
}
});
Backbone.ModelBinder.CollectionConverter = function(collection){
2013-01-23 05:58:17 +00:00
this._collection = collection;
if(!this._collection){
2013-01-23 05:58:17 +00:00
throw 'Collection must be defined';
}
_.bindAll(this, 'convert');
};
_.extend(Backbone.ModelBinder.CollectionConverter.prototype, {
convert: function(direction, value){
2013-01-23 05:58:17 +00:00
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){
2013-01-23 05:58:17 +00:00
var foundEls, elCount, foundEl, attributeName;
var bindings = {};
foundEls = $('[' + attributeType + ']', rootEl);
for(elCount = 0; elCount < foundEls.length; elCount++){
2013-01-23 05:58:17 +00:00
foundEl = foundEls[elCount];
attributeName = $(foundEl).attr(attributeType);
if(!bindings[attributeName]){
var attributeBinding = {selector: '[' + attributeType + '="' + attributeName + '"]'};
2013-01-23 05:58:17 +00:00
bindings[attributeName] = attributeBinding;
if(converter){
2013-01-23 05:58:17 +00:00
bindings[attributeName].converter = converter;
}
if(elAttribute){
2013-01-23 05:58:17 +00:00
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};
2013-01-23 05:58:17 +00:00
if(value.converter){
2013-01-23 05:58:17 +00:00
elementBinding.converter = value.converter;
}
if(value.elAttribute){
2013-01-23 05:58:17 +00:00
elementBinding.elAttribute = value.elAttribute;
}
if(!destination[key]){
2013-01-23 05:58:17 +00:00
destination[key] = elementBinding;
}
else {
destination[key] = [destination[key], elementBinding];
}
});
return destination;
};
return Backbone.ModelBinder;
}));