/* knockback-full-stack.js 0.19.0 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("jquery")); else if(typeof define === 'function' && define.amd) define(["jquery"], factory); else if(typeof exports === 'object') exports["kb"] = factory(require("jquery")); else root["kb"] = factory(root["jQuery"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_18__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(1); __webpack_require__(2); __webpack_require__(3); __webpack_require__(4); __webpack_require__(5); __webpack_require__(6); __webpack_require__(7); __webpack_require__(8); __webpack_require__(9); __webpack_require__(10); __webpack_require__(11); __webpack_require__(13); __webpack_require__(14); __webpack_require__(15); __webpack_require__(16); __webpack_require__(17); module.exports = __webpack_require__(12); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var COMPARE_ASCENDING, COMPARE_DESCENDING, COMPARE_EQUAL, kb, ko, _, __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; }; kb = __webpack_require__(5); _ = kb._; ko = kb.ko; COMPARE_EQUAL = 0; COMPARE_ASCENDING = -1; COMPARE_DESCENDING = 1; kb.compare = function(value_a, value_b) { if (_.isString(value_a)) { return value_a.localeCompare("" + value_b); } if (_.isString(value_b)) { return value_b.localeCompare("" + value_a); } if (value_a === value_b) { return COMPARE_EQUAL; } else { if (value_a < value_b) { return COMPARE_ASCENDING; } else { return COMPARE_DESCENDING; } } }; kb.CollectionObservable = (function() { CollectionObservable.extend = kb.extend; function CollectionObservable(collection, options) { return kb.ignore((function(_this) { return function() { var create_options, observable, _ref; if (_.isUndefined(options) && !(collection instanceof kb.Collection)) { _ref = [new kb.Collection(), collection], collection = _ref[0], options = _ref[1]; } else if (_.isArray(collection)) { collection = new kb.Collection(collection); } options || (options = {}); observable = kb.utils.wrappedObservable(_this, ko.observableArray([])); observable.__kb_is_co = true; _this.in_edit = 0; _this.__kb || (_this.__kb = {}); _this.__kb._onCollectionChange = _.bind(_this._onCollectionChange, _this); options = kb.utils.collapseOptions(options); if (options.auto_compact) { _this.auto_compact = true; } if (options.sort_attribute) { _this._comparator = ko.observable(_this._attributeComparator(options.sort_attribute)); } else { _this._comparator = ko.observable(options.comparator); } if (options.filters) { _this._filters = ko.observableArray(_.isArray(options.filters) ? options.filters : options.filters ? [options.filters] : void 0); } else { _this._filters = ko.observableArray([]); } create_options = _this.create_options = { store: kb.Store.useOptionsOrCreate(options, collection, observable) }; _this.path = options.path; create_options.factory = kb.utils.wrappedFactory(observable, _this._shareOrCreateFactory(options)); create_options.path = kb.utils.pathJoin(options.path, 'models'); create_options.creator = create_options.factory.creatorForPath(null, create_options.path); if (create_options.creator) { _this.models_only = create_options.creator.models_only; } kb.publishMethods(observable, _this, ['destroy', 'shareOptions', 'filters', 'comparator', 'sortAttribute', 'viewModelByModel', 'hasViewModels']); _this._collection = ko.observable(collection); observable.collection = _this.collection = ko.dependentObservable({ read: function() { return _this._collection(); }, write: function(new_collection) { return kb.ignore(function() { var previous_collection; if ((previous_collection = _this._collection()) === new_collection) { return; } if (previous_collection) { previous_collection.unbind('all', _this.__kb._onCollectionChange); } if (new_collection) { new_collection.bind('all', _this.__kb._onCollectionChange); } return _this._collection(new_collection); }); } }); if (collection) { collection.bind('all', _this.__kb._onCollectionChange); } _this._mapper = ko.dependentObservable(function() { var comparator, current_collection, filter, filters, models, view_models, _i, _len; comparator = _this._comparator(); filters = _this._filters(); if (filters) { for (_i = 0, _len = filters.length; _i < _len; _i++) { filter = filters[_i]; ko.utils.unwrapObservable(filter); } } current_collection = _this._collection(); if (_this.in_edit) { return; } observable = kb.utils.wrappedObservable(_this); if (current_collection) { models = current_collection.models; } if (!models || (current_collection.models.length === 0)) { view_models = []; } else { models = _.filter(models, function(model) { return !filters.length || _this._selectModel(model); }); if (comparator) { view_models = _.map(models, function(model) { return _this._createViewModel(model); }).sort(comparator); } else { if (_this.models_only) { view_models = filters.length ? models : models.slice(); } else { view_models = _.map(models, function(model) { return _this._createViewModel(model); }); } } } _this.in_edit++; observable(view_models); return _this.in_edit--; }); observable.subscribe(_.bind(_this._onObservableArrayChange, _this)); !kb.statistics || kb.statistics.register('CollectionObservable', _this); return observable; }; })(this)); } CollectionObservable.prototype.destroy = function() { var array, collection, observable; observable = kb.utils.wrappedObservable(this); collection = kb.peek(this._collection); if (collection) { collection.unbind('all', this.__kb._onCollectionChange); array = kb.peek(observable); array.splice(0, array.length); } this.collection.dispose(); this._collection = observable.collection = this.collection = null; this._mapper.dispose(); this._mapper = null; kb.release(this._filters); this._filters = null; this._comparator(null); this._comparator = null; this.create_options = null; observable.collection = null; kb.utils.wrappedDestroy(this); return !kb.statistics || kb.statistics.unregister('CollectionObservable', this); }; CollectionObservable.prototype.shareOptions = function() { var observable; observable = kb.utils.wrappedObservable(this); return { store: kb.utils.wrappedStore(observable), factory: kb.utils.wrappedFactory(observable) }; }; CollectionObservable.prototype.filters = function(filters) { if (filters) { return this._filters(_.isArray(filters) ? filters : [filters]); } else { return this._filters([]); } }; CollectionObservable.prototype.comparator = function(comparator) { return this._comparator(comparator); }; CollectionObservable.prototype.sortAttribute = function(sort_attribute) { return this._comparator(sort_attribute ? this._attributeComparator(sort_attribute) : null); }; CollectionObservable.prototype.viewModelByModel = function(model) { var id_attribute; if (this.models_only) { return null; } id_attribute = model.hasOwnProperty(model.idAttribute) ? model.idAttribute : 'cid'; return _.find(kb.peek(kb.utils.wrappedObservable(this)), function(test) { var _ref; if (test != null ? (_ref = test.__kb) != null ? _ref.object : void 0 : void 0) { return test.__kb.object[id_attribute] === model[id_attribute]; } else { return false; } }); }; CollectionObservable.prototype.hasViewModels = function() { return !this.models_only; }; CollectionObservable.prototype.compact = function() { return kb.ignore((function(_this) { return function() { var observable; observable = kb.utils.wrappedObservable(_this); if (!kb.utils.wrappedStoreIsOwned(observable)) { return; } kb.utils.wrappedStore(observable).clear(); return _this._collection.notifySubscribers(_this._collection()); }; })(this)); }; CollectionObservable.prototype._shareOrCreateFactory = function(options) { var absolute_models_path, existing_creator, factories, factory; absolute_models_path = kb.utils.pathJoin(options.path, 'models'); factories = options.factories; if ((factory = options.factory)) { if ((existing_creator = factory.creatorForPath(null, absolute_models_path)) && (!factories || (factories['models'] === existing_creator))) { if (!factories) { return factory; } if (factory.hasPathMappings(factories, options.path)) { return factory; } } } factory = new kb.Factory(options.factory); if (factories) { factory.addPathMappings(factories, options.path); } if (!factory.creatorForPath(null, absolute_models_path)) { if (options.hasOwnProperty('models_only')) { if (options.models_only) { factory.addPathMapping(absolute_models_path, { models_only: true }); } else { factory.addPathMapping(absolute_models_path, kb.ViewModel); } } else if (options.view_model) { factory.addPathMapping(absolute_models_path, options.view_model); } else if (options.create) { factory.addPathMapping(absolute_models_path, { create: options.create }); } else { factory.addPathMapping(absolute_models_path, kb.ViewModel); } } return factory; }; CollectionObservable.prototype._onCollectionChange = function(event, arg) { return kb.ignore((function(_this) { return function() { var collection, comparator, observable, view_model; if (_this.in_edit) { return; } switch (event) { case 'reset': if (_this.auto_compact) { _this.compact(); } else { _this._collection.notifySubscribers(_this._collection()); } break; case 'sort': case 'resort': _this._collection.notifySubscribers(_this._collection()); break; case 'new': case 'add': if (!_this._selectModel(arg)) { return; } observable = kb.utils.wrappedObservable(_this); collection = _this._collection(); if (collection.indexOf(arg) === -1) { return; } if ((view_model = _this.viewModelByModel(arg))) { return; } _this.in_edit++; view_model = _this._createViewModel(arg); if ((comparator = _this._comparator())) { observable().push(view_model); observable.sort(comparator); } else { observable.splice(collection.indexOf(arg), 0, view_model); } _this.in_edit--; break; case 'remove': case 'destroy': _this._onModelRemove(arg); break; case 'change': if (!_this._selectModel(arg)) { _this._onModelRemove(arg); } else { view_model = _this.models_only ? arg : _this.viewModelByModel(arg); if (view_model) { if ((comparator = _this._comparator())) { observable = kb.utils.wrappedObservable(_this); _this.in_edit++; observable.sort(comparator); _this.in_edit--; } } else { _this._onCollectionChange('add', arg); } } } }; })(this)); }; CollectionObservable.prototype._onModelRemove = function(model) { var observable, view_model; view_model = this.models_only ? model : this.viewModelByModel(model); if (!view_model) { return; } observable = kb.utils.wrappedObservable(this); this.in_edit++; observable.remove(view_model); return this.in_edit--; }; CollectionObservable.prototype._onObservableArrayChange = function(models_or_view_models) { return kb.ignore((function(_this) { return function() { var collection, has_filters, model, models, observable, view_model, view_models, _i, _len; if (_this.in_edit) { return; } (_this.models_only && (!models_or_view_models.length || kb.utils.hasModelSignature(models_or_view_models[0]))) || (!_this.models_only && (!models_or_view_models.length || (_.isObject(models_or_view_models[0]) && !kb.utils.hasModelSignature(models_or_view_models[0])))) || kb._throwUnexpected(_this, 'incorrect type passed'); observable = kb.utils.wrappedObservable(_this); collection = kb.peek(_this._collection); has_filters = kb.peek(_this._filters).length; if (!collection) { return; } view_models = models_or_view_models; if (_this.models_only) { models = _.filter(models_or_view_models, function(model) { return !has_filters || _this._selectModel(model); }); } else { !has_filters || (view_models = []); models = []; for (_i = 0, _len = models_or_view_models.length; _i < _len; _i++) { view_model = models_or_view_models[_i]; model = kb.utils.wrappedObject(view_model); if (has_filters) { if (!_this._selectModel(model)) { continue; } view_models.push(view_model); } _this.create_options.store.findOrReplace(model, _this.create_options.creator, view_model); models.push(model); } } _this.in_edit++; (models_or_view_models.length === view_models.length) || observable(view_models); _.isEqual(collection.models, models) || collection.reset(models); _this.in_edit--; }; })(this)); }; CollectionObservable.prototype._attributeComparator = function(sort_attribute) { var modelAttributeCompare; modelAttributeCompare = function(model_a, model_b) { var attribute_name; attribute_name = ko.utils.unwrapObservable(sort_attribute); return kb.compare(model_a.get(attribute_name), model_b.get(attribute_name)); }; return (this.models_only ? modelAttributeCompare : function(model_a, model_b) { return modelAttributeCompare(kb.utils.wrappedModel(model_a), kb.utils.wrappedModel(model_b)); }); }; CollectionObservable.prototype._createViewModel = function(model) { if (this.models_only) { return model; } return this.create_options.store.findOrCreate(model, this.create_options); }; CollectionObservable.prototype._selectModel = function(model) { var filter, filters, _i, _len, _ref; filters = kb.peek(this._filters); for (_i = 0, _len = filters.length; _i < _len; _i++) { filter = filters[_i]; filter = kb.peek(filter); if (_.isFunction(filter)) { if (!filter(model)) { return false; } } else if (_.isArray(filter)) { if (_ref = model.id, __indexOf.call(filter, _ref) < 0) { return false; } } else { if (model.id !== filter) { return false; } } } return true; }; return CollectionObservable; })(); kb.collectionObservable = function(collection, options) { return new kb.CollectionObservable(collection, options); }; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var kb, ko, _, __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; }; kb = __webpack_require__(5); _ = kb._; ko = kb.ko; kb.EventWatcher = (function() { EventWatcher.useOptionsOrCreate = function(options, emitter, obj, callback_options) { if (options.event_watcher) { if (!(options.event_watcher.emitter() === emitter || (options.event_watcher.model_ref === emitter))) { kb._throwUnexpected(this, 'emitter not matching'); } return kb.utils.wrappedEventWatcher(obj, options.event_watcher).registerCallbacks(obj, callback_options); } else { kb.utils.wrappedEventWatcherIsOwned(obj, true); return kb.utils.wrappedEventWatcher(obj, new kb.EventWatcher(emitter)).registerCallbacks(obj, callback_options); } }; function EventWatcher(emitter, obj, callback_options) { this._onModelUnloaded = __bind(this._onModelUnloaded, this); this._onModelLoaded = __bind(this._onModelLoaded, this); this.__kb || (this.__kb = {}); this.__kb.callbacks = {}; this.__kb._onModelLoaded = _.bind(this._onModelLoaded, this); this.__kb._onModelUnloaded = _.bind(this._onModelUnloaded, this); if (callback_options) { this.registerCallbacks(obj, callback_options); } if (emitter) { this.emitter(emitter); } else { this.ee = null; } } EventWatcher.prototype.destroy = function() { this.emitter(null); this.__kb.callbacks = null; return kb.utils.wrappedDestroy(this); }; EventWatcher.prototype.emitter = function(new_emitter) { var callbacks, event_name, info, list, previous_emitter, _i, _len, _ref; if ((arguments.length === 0) || (this.ee === new_emitter)) { return this.ee; } if (this.model_ref) { this.model_ref.unbind('loaded', this.__kb._onModelLoaded); this.model_ref.unbind('unloaded', this.__kb._onModelUnloaded); this.model_ref.release(); this.model_ref = null; } if (kb.Backbone && kb.Backbone.ModelRef && (new_emitter instanceof kb.Backbone.ModelRef)) { this.model_ref = new_emitter; this.model_ref.retain(); this.model_ref.bind('loaded', this.__kb._onModelLoaded); this.model_ref.bind('unloaded', this.__kb._onModelUnloaded); new_emitter = this.model_ref.model(); } else { delete this.model_ref; } previous_emitter = this.ee; this.ee = new_emitter; _ref = this.__kb.callbacks; for (event_name in _ref) { callbacks = _ref[event_name]; if (previous_emitter) { previous_emitter.unbind(event_name, callbacks.fn); } if (new_emitter) { this.ee.bind(event_name, callbacks.fn); } list = callbacks.list; for (_i = 0, _len = list.length; _i < _len; _i++) { info = list[_i]; if (info.emitter) { info.emitter(this.ee); } } } return new_emitter; }; EventWatcher.prototype.registerCallbacks = function(obj, callback_info) { var callbacks, event_name, event_names, event_selector, info, list, _i, _len; obj || kb._throwMissing(this, 'obj'); callback_info || kb._throwMissing(this, 'info'); event_selector = callback_info.event_selector ? callback_info.event_selector : 'change'; event_names = event_selector.split(' '); for (_i = 0, _len = event_names.length; _i < _len; _i++) { event_name = event_names[_i]; if (!event_name) { continue; } callbacks = this.__kb.callbacks[event_name]; if (!callbacks) { list = []; callbacks = { list: list, fn: (function(_this) { return function(model) { var info, _j, _len1; for (_j = 0, _len1 = list.length; _j < _len1; _j++) { info = list[_j]; if (info.update && !info.rel_fn) { if (model && info.key && (model.hasChanged && !model.hasChanged(ko.utils.unwrapObservable(info.key)))) { continue; } !kb.statistics || kb.statistics.addModelEvent({ name: event_name, model: model, key: info.key, path: info.path }); info.update(); } } return null; }; })(this) }; this.__kb.callbacks[event_name] = callbacks; if (this.ee) { this.ee.bind(event_name, callbacks.fn); } } info = _.defaults({ obj: obj }, callback_info); callbacks.list.push(info); } if (this.ee) { if (__indexOf.call(event_names, 'change') >= 0) { info.unbind_fn = kb.orm.bind(this.ee, info.key, info.update, info.path); } info.emitter(this.ee) && info.emitter; } }; EventWatcher.prototype.releaseCallbacks = function(obj) { var callbacks, event_name, index, info, _ref, _ref1; if (!this.__kb.callbacks || !this.ee) { return; } _ref = this.__kb.callbacks; for (event_name in _ref) { callbacks = _ref[event_name]; _ref1 = callbacks.list; for (index in _ref1) { info = _ref1[index]; if (info.obj !== obj) { continue; } callbacks.list.splice(index, 1); if (info.unbind_fn) { info.unbind_fn(); info.unbind_fn = null; } if (!kb.wasReleased(obj) && info.emitter) { info.emitter(null); } return; } } }; EventWatcher.prototype._onModelLoaded = function(model) { var callbacks, event_name, info, _i, _len, _ref, _ref1; this.ee = model; _ref = this.__kb.callbacks; for (event_name in _ref) { callbacks = _ref[event_name]; model.bind(event_name, callbacks.fn); _ref1 = callbacks.list; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { info = _ref1[_i]; info.unbind_fn = kb.orm.bind(model, info.key, info.update, info.path); if (info.emitter) { info.emitter(model); } } } }; EventWatcher.prototype._onModelUnloaded = function(model) { var callbacks, event_name, info, list, _i, _len, _ref; this.ee = null; _ref = this.__kb.callbacks; for (event_name in _ref) { callbacks = _ref[event_name]; model.unbind(event_name, callbacks.fn); list = callbacks.list; for (_i = 0, _len = list.length; _i < _len; _i++) { info = list[_i]; if (info.unbind_fn) { info.unbind_fn(); info.unbind_fn = null; } if (info.emitter) { info.emitter(null); } } } }; return EventWatcher; })(); kb.emitterObservable = function(emitter, observable) { return new kb.EventWatcher(emitter, observable); }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var kb, _; kb = __webpack_require__(5); _ = kb._; kb.Factory = (function() { Factory.useOptionsOrCreate = function(options, obj, owner_path) { var factory; if (options.factory && (!options.factories || (options.factories && options.factory.hasPathMappings(options.factories, owner_path)))) { return kb.utils.wrappedFactory(obj, options.factory); } factory = kb.utils.wrappedFactory(obj, new kb.Factory(options.factory)); if (options.factories) { factory.addPathMappings(options.factories, owner_path); } return factory; }; function Factory(parent_factory) { this.parent_factory = parent_factory; this.paths = {}; } Factory.prototype.hasPath = function(path) { return this.paths.hasOwnProperty(path) || (this.parent_factory && this.parent_factory.hasPath(path)); }; Factory.prototype.addPathMapping = function(path, create_info) { return this.paths[path] = create_info; }; Factory.prototype.addPathMappings = function(factories, owner_path) { var create_info, path; for (path in factories) { create_info = factories[path]; this.paths[kb.utils.pathJoin(owner_path, path)] = create_info; } }; Factory.prototype.hasPathMappings = function(factories, owner_path) { var all_exist, creator, existing_creator, path; all_exist = true; for (path in factories) { creator = factories[path]; all_exist &= (existing_creator = this.creatorForPath(null, kb.utils.pathJoin(owner_path, path))) && (creator === existing_creator); } return all_exist; }; Factory.prototype.creatorForPath = function(obj, path) { var creator; if ((creator = this.paths[path])) { if (creator.view_model) { return creator.view_model; } else { return creator; } } if (this.parent_factory) { if ((creator = this.parent_factory.creatorForPath(obj, path))) { return creator; } } return null; }; return Factory; })(); /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var $, kb, ko, onReady, window, _, _ko_applyBindings; window = window != null ? window : global; kb = __webpack_require__(5); _ = kb._; ko = kb.ko; $ = kb.$; kb.RECUSIVE_AUTO_INJECT = true; ko.bindingHandlers['inject'] = { 'init': function(element, value_accessor, all_bindings_accessor, view_model) { return kb.Inject.inject(ko.utils.unwrapObservable(value_accessor()), view_model, element, value_accessor, all_bindings_accessor); } }; kb.Inject = (function() { function Inject() {} Inject.inject = function(data, view_model, element, value_accessor, all_bindings_accessor, nested) { var inject, result, wrapper; inject = function(data) { var key, target, value; if (_.isFunction(data)) { view_model = new data(view_model, element, value_accessor, all_bindings_accessor); kb.releaseOnNodeRemove(view_model, element); } else { if (data.view_model) { view_model = new data.view_model(view_model, element, value_accessor, all_bindings_accessor); kb.releaseOnNodeRemove(view_model, element); } for (key in data) { value = data[key]; if (key === 'view_model') { continue; } if (key === 'create') { value(view_model, element, value_accessor, all_bindings_accessor); } else if (_.isObject(value) && !_.isFunction(value)) { target = nested || (value && value.create) ? {} : view_model; view_model[key] = kb.Inject.inject(value, target, element, value_accessor, all_bindings_accessor, true); } else { view_model[key] = value; } } } return view_model; }; if (nested) { return inject(data); } else { result = (wrapper = ko.dependentObservable(function() { return inject(data); }))(); wrapper.dispose(); return result; } }; Inject.injectViewModels = function(root) { var afterBinding, app, beforeBinding, data, expression, findElements, options, results, _i, _len; results = []; findElements = function(el) { var attr, child_el, _i, _len, _ref; if (!el.__kb_injected) { if (el.attributes && (attr = _.find(el.attributes, function(attr) { return attr.name === 'kb-inject'; }))) { el.__kb_injected = true; results.push({ el: el, view_model: {}, binding: attr.value }); } } _ref = el.childNodes; for (_i = 0, _len = _ref.length; _i < _len; _i++) { child_el = _ref[_i]; findElements(child_el); } }; if (!root && (window != null ? window.document : void 0)) { root = window.document; } findElements(root); for (_i = 0, _len = results.length; _i < _len; _i++) { app = results[_i]; if (expression = app.binding) { (expression.search(/[:]/) < 0) || (expression = "{" + expression + "}"); data = (new Function("", "return ( " + expression + " )"))(); data || (data = {}); (!data.options) || (options = data.options, delete data.options); options || (options = {}); app.view_model = kb.Inject.inject(data, app.view_model, app.el, null, null, true); afterBinding = app.view_model.afterBinding || options.afterBinding; beforeBinding = app.view_model.beforeBinding || options.beforeBinding; } if (beforeBinding) { beforeBinding(app.view_model, app.el, options); } kb.applyBindings(app.view_model, app.el, options); if (afterBinding) { afterBinding(app.view_model, app.el, options); } } return results; }; return Inject; })(); _ko_applyBindings = ko.applyBindings; ko.applyBindings = function(context, element) { var results; results = kb.RECUSIVE_AUTO_INJECT ? kb.injectViewModels(element) : []; if (!results.length) { return _ko_applyBindings.apply(this, arguments); } }; kb.injectViewModels = kb.Inject.injectViewModels; if (typeof document !== "undefined" && document !== null) { if ($) { $(function() { return kb.injectViewModels(); }); } else { (onReady = function() { if (document.readyState !== "complete") { return setTimeout(onReady, 0); } return kb.injectViewModels(); })(); } } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var Backbone, copyProps, kb, ko, window, _; window = window != null ? window : global; ko = __webpack_require__(23); copyProps = function(dest, source) { var key, value; for (key in source) { value = source[key]; dest[key] = value; } return dest; }; // Shared empty constructor function to aid in prototype-chain creation. var ctor = function(){}; // Helper function to correctly set up the prototype chain, for subclasses. // Similar to 'goog.inherits', but uses a hash of prototype properties and // class properties to be extended. var inherits = function(parent, protoProps, staticProps) { var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your extend definition), or defaulted // by us to simply call the parent's constructor. if (protoProps && protoProps.hasOwnProperty('constructor')) { child = protoProps.constructor; } else { child = function(){ parent.apply(this, arguments); }; } // Inherit class (static) properties from parent. copyProps(child, parent); // Set the prototype chain to inherit from parent, without calling // parent's constructor function. ctor.prototype = parent.prototype; child.prototype = new ctor(); // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps) copyProps(child.prototype, protoProps); // Add static properties to the constructor function, if supplied. if (staticProps) copyProps(child, staticProps); // Correctly set child's 'prototype.constructor'. child.prototype.constructor = child; // Set a convenience property in case the parent's prototype is needed later. child.__super__ = parent.prototype; return child; }; // The self-propagating extend function that BacLCone classes use. var extend = function (protoProps, classProps) { var child = inherits(this, protoProps, classProps); child.extend = this.extend; return child; }; ; module.exports = kb = (function() { var _ref; function kb() {} kb.VERSION = '0.18.6'; kb.TYPE_UNKNOWN = 0; kb.TYPE_SIMPLE = 1; kb.TYPE_ARRAY = 2; kb.TYPE_MODEL = 3; kb.TYPE_COLLECTION = 4; kb.wasReleased = function(obj) { return !obj || obj.__kb_released; }; kb.isReleaseable = function(obj, depth) { var key, value; if (depth == null) { depth = 0; } if ((!obj || (obj !== Object(obj))) || obj.__kb_released) { return false; } else if (ko.isObservable(obj) || (obj instanceof kb.ViewModel)) { return true; } else if ((typeof obj === 'function') || (obj instanceof kb.Model) || (obj instanceof kb.Collection)) { return false; } else if ((typeof obj.dispose === 'function') || (typeof obj.destroy === 'function') || (typeof obj.release === 'function')) { return true; } else if (depth < 1) { for (key in obj) { value = obj[key]; if ((key !== '__kb') && kb.isReleaseable(value, depth + 1)) { return true; } } } return false; }; kb.release = function(obj) { var array, index, value; if (!kb.isReleaseable(obj)) { return; } if (_.isArray(obj)) { for (index in obj) { value = obj[index]; if (kb.isReleaseable(value)) { obj[index] = null; kb.release(value); } } return; } obj.__kb_released = true; if (ko.isObservable(obj) && _.isArray(array = kb.peek(obj))) { if (obj.__kb_is_co || (obj.__kb_is_o && (obj.valueType() === kb.TYPE_COLLECTION))) { if (obj.destroy) { obj.destroy(); } else if (obj.dispose) { obj.dispose(); } } else if (array.length) { for (index in array) { value = array[index]; if (kb.isReleaseable(value)) { array[index] = null; kb.release(value); } } } } else if (typeof obj.release === 'function') { obj.release(); } else if (typeof obj.destroy === 'function') { obj.destroy(); } else if (typeof obj.dispose === 'function') { obj.dispose(); } else if (!ko.isObservable(obj)) { this.releaseKeys(obj); } }; kb.releaseKeys = function(obj) { var key, value; for (key in obj) { value = obj[key]; if ((key !== '__kb') && kb.isReleaseable(value)) { obj[key] = null; kb.release(value); } } }; kb.releaseOnNodeRemove = function(view_model, node) { view_model || kb._throwUnexpected(this, 'missing view model'); node || kb._throwUnexpected(this, 'missing node'); return ko.utils.domNodeDisposal.addDisposeCallback(node, function() { return kb.release(view_model); }); }; kb.renderTemplate = function(template, view_model, options) { var document, el, observable; if (options == null) { options = {}; } if (!(document = window != null ? window.document : void 0)) { return typeof console !== "undefined" && console !== null ? console.log('renderTemplate: document is undefined') : void 0; } el = document.createElement('div'); observable = ko.renderTemplate(template, view_model, options, el, 'replaceChildren'); if (el.children.length === 1) { el = el.children[0]; } kb.releaseOnNodeRemove(view_model, el); observable.dispose(); if (view_model.afterRender && !options.afterRender) { view_model.afterRender(el); } return el; }; kb.applyBindings = function(view_model, node) { ko.applyBindings(view_model, node); return kb.releaseOnNodeRemove(view_model, node); }; kb.getValue = function(model, key, args) { if (!model) { return; } if (_.isFunction(model[key]) && kb.orm.useFunction(model, key)) { return model[key](); } if (!args) { return model.get(key); } return model.get.apply(model, _.map([key].concat(args), function(value) { return kb.peek(value); })); }; kb.setValue = function(model, key, value) { var attributes; if (!model) { return; } if (_.isFunction(model[key]) && kb.orm.useFunction(model, key)) { return model[key](value); } (attributes = {})[key] = value; return model.set(attributes); }; kb.ignore = ((_ref = ko.dependencyDetection) != null ? _ref.ignore : void 0) || function(callback, callbackTarget, callbackArgs) { var value; value = null; ko.dependentObservable(function() { return value = callback.apply(callbackTarget, callbackArgs || []); }).dispose(); return value; }; kb.extend = extend; kb._throwMissing = function(instance, message) { throw "" + (_.isString(instance) ? instance : instance.constructor.name) + ": " + message + " is missing"; }; kb._throwUnexpected = function(instance, message) { throw "" + (_.isString(instance) ? instance : instance.constructor.name) + ": " + message + " is unexpected"; }; kb.publishMethods = function(observable, instance, methods) { var fn, _i, _len; for (_i = 0, _len = methods.length; _i < _len; _i++) { fn = methods[_i]; observable[fn] = kb._.bind(instance[fn], instance); } }; kb.peek = function(obs) { if (!ko.isObservable(obs)) { return obs; } if (obs.peek) { return obs.peek(); } return kb.ignore(function() { return obs(); }); }; return kb; })(); if (window.Parse) { Backbone = kb.Parse = window.Parse; _ = kb._ = window.Parse._; } else { Backbone = kb.Backbone = __webpack_require__(21); _ = kb._ = __webpack_require__(22); } kb.ko = ko; kb.Collection = Backbone.Collection; kb.Model = Backbone.Object || Backbone.Model; kb.Events = Backbone.Events; kb.$ = window.jQuery || window.$; try { kb.$ || (kb.$ = __webpack_require__(18)); } catch (_error) {} /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var kb, ko, _; kb = __webpack_require__(5); _ = kb._; ko = kb.ko; kb.Observable = (function() { function Observable(model, options, _vm) { this._vm = _vm != null ? _vm : {}; return kb.ignore((function(_this) { return function() { var create_options, event_watcher, observable; options || kb._throwMissing(_this, 'options'); if (_.isString(options) || ko.isObservable(options)) { create_options = _this.create_options = { key: options }; } else { create_options = _this.create_options = kb.utils.collapseOptions(options); } _this.key = create_options.key; delete create_options.key; _this.key || kb._throwMissing(_this, 'key'); !create_options.args || (_this.args = create_options.args, delete create_options.args); !create_options.read || (_this.read = create_options.read, delete create_options.read); !create_options.write || (_this.write = create_options.write, delete create_options.write); event_watcher = create_options.event_watcher; delete create_options.event_watcher; _this._vo = ko.observable(null); _this._model = ko.observable(); observable = kb.utils.wrappedObservable(_this, ko.dependentObservable({ read: function() { var arg, args, _i, _len, _model, _ref; _model = _this._model(); _ref = args = [_this.key].concat(_this.args || []); for (_i = 0, _len = _ref.length; _i < _len; _i++) { arg = _ref[_i]; ko.utils.unwrapObservable(arg); } if (_this.read) { _this.update(_this.read.apply(_this._vm, args)); } else if (!_.isUndefined(_model)) { kb.ignore(function() { return _this.update(kb.getValue(_model, kb.peek(_this.key), _this.args)); }); } return ko.utils.unwrapObservable(_this._vo()); }, write: function(new_value) { return kb.ignore(function() { var unwrapped_new_value, _model; unwrapped_new_value = kb.utils.unwrapModels(new_value); _model = kb.peek(_this._model); if (_this.write) { _this.write.call(_this._vm, unwrapped_new_value); new_value = kb.getValue(_model, kb.peek(_this.key), _this.args); } else if (_model) { kb.setValue(_model, kb.peek(_this.key), unwrapped_new_value); } return _this.update(new_value); }); }, owner: _this._vm })); observable.__kb_is_o = true; create_options.store = kb.utils.wrappedStore(observable, create_options.store); create_options.path = kb.utils.pathJoin(create_options.path, _this.key); if (create_options.factories && ((typeof create_options.factories === 'function') || create_options.factories.create)) { create_options.factory = kb.utils.wrappedFactory(observable, new kb.Factory(create_options.factory)); create_options.factory.addPathMapping(create_options.path, create_options.factories); } else { create_options.factory = kb.Factory.useOptionsOrCreate(create_options, observable, create_options.path); } delete create_options.factories; kb.publishMethods(observable, _this, ['value', 'valueType', 'destroy']); observable.model = _this.model = ko.dependentObservable({ read: function() { return ko.utils.unwrapObservable(_this._model); }, write: function(new_model) { return kb.ignore(function() { var new_value; if (_this.__kb_released || (kb.peek(_this._model) === new_model)) { return; } new_value = kb.getValue(new_model, kb.peek(_this.key), _this.args); _this._model(new_model); if (!new_model) { return _this.update(null); } else if (!_.isUndefined(new_value)) { return _this.update(new_value); } }); } }); kb.EventWatcher.useOptionsOrCreate({ event_watcher: event_watcher }, model, _this, { emitter: _this.model, update: _.bind(_this.update, _this), key: _this.key, path: create_options.path }); _this.__kb_value || _this.update(); if (kb.LocalizedObservable && create_options.localizer) { observable = new create_options.localizer(observable); delete create_options.localizer; } if (kb.DefaultObservable && create_options.hasOwnProperty('default')) { observable = kb.defaultObservable(observable, create_options["default"]); delete create_options["default"]; } return observable; }; })(this)); } Observable.prototype.destroy = function() { var observable; observable = kb.utils.wrappedObservable(this); this.__kb_released = true; kb.release(this.__kb_value); this.__kb_value = null; this.model.dispose(); this.model = observable.model = null; return kb.utils.wrappedDestroy(this); }; Observable.prototype.value = function() { return this.__kb_value; }; Observable.prototype.valueType = function() { var new_value; new_value = kb.getValue(kb.peek(this._model), kb.peek(this.key)); this.value_type || this._updateValueObservable(new_value); return this.value_type; }; Observable.prototype.update = function(new_value) { var new_type, value; if (this.__kb_released) { return; } if (!arguments.length) { new_value = kb.getValue(kb.peek(this._model), kb.peek(this.key)); } (new_value !== void 0) || (new_value = null); new_type = kb.utils.valueType(new_value); if (!this.__kb_value || (this.__kb_value.__kb_released || (this.__kb_value.__kb_null && new_value))) { this.__kb_value = void 0; this.value_type = void 0; } value = this.__kb_value; if (_.isUndefined(this.value_type) || (this.value_type !== new_type && new_type !== kb.TYPE_UNKNOWN)) { if ((this.value_type === kb.TYPE_COLLECTION) && (new_type === kb.TYPE_ARRAY)) { return value(new_value); } else { return this._updateValueObservable(new_value); } } else if (this.value_type === kb.TYPE_MODEL) { if (typeof value.model === 'function') { if (value.model() !== new_value) { return value.model(new_value); } } else if (kb.utils.wrappedObject(value) !== new_value) { return this._updateValueObservable(new_value); } } else if (this.value_type === kb.TYPE_COLLECTION) { if (value.collection() !== new_value) { return value.collection(new_value); } } else { if (value() !== new_value) { return value(new_value); } } }; Observable.prototype._updateValueObservable = function(new_value) { var create_options, creator, previous_value, value; create_options = this.create_options; create_options.creator = kb.utils.inferCreator(new_value, create_options.factory, create_options.path, kb.peek(this._model), this.key); this.value_type = kb.TYPE_UNKNOWN; creator = create_options.creator; previous_value = this.__kb_value; this.__kb_value = void 0; if (previous_value) { kb.release(previous_value); } if (creator) { if (create_options.store) { value = create_options.store.findOrCreate(new_value, create_options); } else { if (creator.models_only) { value = new_value; this.value_type = kb.TYPE_SIMPLE; } else if (creator.create) { value = creator.create(new_value, create_options); } else { value = new creator(new_value, create_options); } } } else { if (_.isArray(new_value)) { this.value_type = kb.TYPE_ARRAY; value = ko.observableArray(new_value); } else { this.value_type = kb.TYPE_SIMPLE; value = ko.observable(new_value); } } if (this.value_type === kb.TYPE_UNKNOWN) { if (!ko.isObservable(value)) { this.value_type = kb.TYPE_MODEL; if (typeof value.model !== 'function') { kb.utils.wrappedObject(value, new_value); } } else if (value.__kb_is_co) { this.value_type = kb.TYPE_COLLECTION; } else { this.value_type = kb.TYPE_SIMPLE; } } this.__kb_value = value; return this._vo(value); }; return Observable; })(); kb.observable = function(model, options, view_model) { return new kb.Observable(model, options, view_model); }; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var AssociatedModel, ORM, ORMAdapter_BackboneAssociations, ORMAdapter_BackboneRelational, ORMAdapter_Supermodel, RelationalModel, Supermodel, kb, root, _; root = typeof window !== "undefined" && window !== null ? window : global; kb = __webpack_require__(5); _ = kb._; ORM = (function() { function ORM() { this.adapters = []; } ORM.prototype.initialize = function() { this.adapters = _.select(this.adapters, function(adapter) { return adapter.isAvailable(); }); return this.initialized = true; }; ORM.prototype.addAdapter = function(adapter) { this.adapters.push(adapter); return this.initialized = false; }; ORM.prototype.keys = function(model) { return this._call('keys', arguments); }; ORM.prototype.bind = function(model) { return this._call('bind', arguments); }; ORM.prototype.useFunction = function(model) { return this._call('useFunction', arguments); }; ORM.prototype._call = function(name, args) { var adpater, result, _i, _len, _ref; if (!this.adapters.length) { return; } if (!this.initialized) { this.initialize(); } _ref = this.adapters; for (_i = 0, _len = _ref.length; _i < _len; _i++) { adpater = _ref[_i]; if (adpater[name] && (result = adpater[name].apply(adpater, args))) { return result; } } }; return ORM; })(); kb.orm = new ORM(); RelationalModel = null; ORMAdapter_BackboneRelational = (function() { function ORMAdapter_BackboneRelational() {} ORMAdapter_BackboneRelational.prototype.isAvailable = function() { var _ref; return !!(RelationalModel = (_ref = kb.Backbone) != null ? _ref.RelationalModel : void 0); }; ORMAdapter_BackboneRelational.prototype.relationType = function(model, key) { var relation; if (!(model instanceof RelationalModel)) { return null; } if (!(relation = _.find(model.getRelations(), function(test) { return test.key === key; }))) { return null; } if (relation.collectionType || _.isArray(relation.keyContents)) { return kb.TYPE_COLLECTION; } else { return kb.TYPE_MODEL; } }; ORMAdapter_BackboneRelational.prototype.bind = function(model, key, update, path) { var event, events, rel_fn, type, _i, _len; if (!(type = this.relationType(model, key))) { return null; } rel_fn = function(model) { !kb.statistics || kb.statistics.addModelEvent({ name: 'update (relational)', model: model, key: key, path: path }); return update(); }; events = kb.Backbone.Relation.prototype.sanitizeOptions ? ['update', 'add', 'remove'] : ['change', 'add', 'remove']; if (type === kb.TYPE_COLLECTION) { for (_i = 0, _len = events.length; _i < _len; _i++) { event = events[_i]; model.bind("" + event + ":" + key, rel_fn); } } else { model.bind("" + events[0] + ":" + key, rel_fn); } return function() { var _j, _len1; if (type === kb.TYPE_COLLECTION) { for (_j = 0, _len1 = events.length; _j < _len1; _j++) { event = events[_j]; model.unbind("" + event + ":" + key, rel_fn); } } else { model.unbind("" + events[0] + ":" + key, rel_fn); } }; }; return ORMAdapter_BackboneRelational; })(); kb.orm.addAdapter(new ORMAdapter_BackboneRelational()); AssociatedModel = null; ORMAdapter_BackboneAssociations = (function() { function ORMAdapter_BackboneAssociations() {} ORMAdapter_BackboneAssociations.prototype.isAvailable = function() { var _ref; return !!(AssociatedModel = (_ref = kb.Backbone) != null ? _ref.AssociatedModel : void 0); }; ORMAdapter_BackboneAssociations.prototype.keys = function(model) { if (!(model instanceof AssociatedModel)) { return null; } return _.map(model.relations, function(test) { return test.key; }); }; ORMAdapter_BackboneAssociations.prototype.relationType = function(model, key) { var relation; if (!(model instanceof AssociatedModel)) { return null; } if (!(relation = _.find(model.relations, function(test) { return test.key === key; }))) { return null; } if (relation.type === 'Many') { return kb.TYPE_COLLECTION; } else { return kb.TYPE_MODEL; } }; return ORMAdapter_BackboneAssociations; })(); kb.orm.addAdapter(new ORMAdapter_BackboneAssociations()); Supermodel = null; ORMAdapter_Supermodel = (function() { function ORMAdapter_Supermodel() {} ORMAdapter_Supermodel.prototype.isAvailable = function() { return !!(Supermodel = root.Supermodel); }; ORMAdapter_Supermodel.prototype.keys = function(model) { if (!(model instanceof Supermodel.Model)) { return null; } return _.keys(model.constructor.associations()); }; ORMAdapter_Supermodel.prototype.relationType = function(model, key) { var relation; if (!(model instanceof Supermodel.Model)) { return null; } if (!(relation = model.constructor.associations()[key])) { return null; } if (relation.add) { return kb.TYPE_COLLECTION; } else { return kb.TYPE_MODEL; } }; ORMAdapter_Supermodel.prototype.bind = function(model, key, update, path) { var rel_fn, type; if (!(type = this.relationType(model, key))) { return null; } rel_fn = function(model, other) { var previous, relation; !kb.statistics || kb.statistics.addModelEvent({ name: 'update (supermodel)', model: model, key: key, path: path }); relation = model.constructor.associations()[key]; previous = model[relation.store]; model[relation.store] = other; update(other); return model[relation.store] = previous; }; if (type === kb.TYPE_MODEL) { model.bind("associate:" + key, rel_fn); return function() { return model.unbind("associate:" + key, rel_fn); }; } }; ORMAdapter_Supermodel.prototype.useFunction = function(model, key) { return !!this.relationType(model, key); }; return ORMAdapter_Supermodel; })(); kb.orm.addAdapter(new ORMAdapter_Supermodel()); /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var kb, _; kb = __webpack_require__(5); _ = kb._; module.exports = kb.Statistics = (function() { function Statistics() { this.model_events_tracker = []; this.registered_tracker = {}; } Statistics.prototype.clear = function() { return this.model_events_tracker = []; }; Statistics.prototype.addModelEvent = function(event) { return this.model_events_tracker.push(event); }; Statistics.prototype.modelEventsStatsString = function() { var event_groups, key, stats_string, value; stats_string = ''; stats_string += "Total Count: " + this.model_events_tracker.length; event_groups = _.groupBy(this.model_events_tracker, function(test) { return "event name: '" + test.name + "', attribute name: '" + test.key + "'"; }); for (key in event_groups) { value = event_groups[key]; stats_string += "\n " + key + ", count: " + value.length; } return stats_string; }; Statistics.prototype.register = function(key, obj) { return this.registeredTracker(key).push(obj); }; Statistics.prototype.unregister = function(key, obj) { var index, type_tracker; type_tracker = this.registeredTracker(key); index = _.indexOf(type_tracker, obj); if (index < 0) { if (typeof console !== "undefined" && console !== null) { console.log("kb.Statistics: failed to unregister type: " + key); } } return type_tracker.splice(index, 1); }; Statistics.prototype.registeredCount = function(type) { var count, type_tracker, _ref; if (type) { return this.registeredTracker(type).length; } count = 0; _ref = this.registered_tracker[type]; for (type in _ref) { type_tracker = _ref[type]; count += type_tracker.length; } return count; }; Statistics.prototype.registeredStatsString = function(success_message) { var stats_string, type, type_tracker, written, _ref; stats_string = ''; _ref = this.registered_tracker; for (type in _ref) { type_tracker = _ref[type]; if (!type_tracker.length) { continue; } if (written) { stats_string += '\n '; } stats_string += "" + (type ? type : 'No Name') + ": " + type_tracker.length; written = true; } if (stats_string) { return stats_string; } else { return success_message; } }; Statistics.prototype.registeredTracker = function(key) { var type_tracker; if (this.registered_tracker.hasOwnProperty(key)) { return this.registered_tracker[key]; } type_tracker = []; this.registered_tracker[key] = type_tracker; return type_tracker; }; return Statistics; })(); /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var kb, ko, _; kb = __webpack_require__(5); _ = kb._; ko = kb.ko; module.exports = kb.Store = (function() { Store.useOptionsOrCreate = function(options, obj, observable) { if (options.store) { options.store.register(obj, observable, options); return kb.utils.wrappedStore(observable, options.store); } else { kb.utils.wrappedStoreIsOwned(observable, true); return kb.utils.wrappedStore(observable, new kb.Store()); } }; function Store() { this.observable_records = []; this.replaced_observables = []; } Store.prototype.destroy = function() { return this.clear(); }; Store.prototype.clear = function() { var record, _i, _len, _ref; _ref = this.observable_records.splice(0, this.observable_records.length); for (_i = 0, _len = _ref.length; _i < _len; _i++) { record = _ref[_i]; kb.release(record.observable); } kb.release(this.replaced_observables); }; Store.prototype.compact = function() { var index, record, removals, _ref, _ref1; removals = []; _ref = this.observable_records; for (index in _ref) { record = _ref[index]; if ((_ref1 = record.observable) != null ? _ref1.__kb_released : void 0) { removals.push(record); } } if (removals.length) { this.observable_records = _.difference(this.observable_records, removals); } }; Store.prototype.register = function(obj, observable, options) { var creator; if (!observable) { return; } if (ko.isObservable(observable) || observable.__kb_is_co) { return; } kb.utils.wrappedObject(observable, obj); obj || (observable.__kb_null = true); creator = options.creator ? options.creator : (options.path && options.factory ? options.factory.creatorForPath(obj, options.path) : null); if (!creator) { creator = observable.constructor; } this.observable_records.push({ obj: obj, observable: observable, creator: creator }); return observable; }; Store.prototype.findIndex = function(obj, creator) { var index, record, removals, _ref; removals = []; if (!obj || (obj instanceof kb.Model)) { _ref = this.observable_records; for (index in _ref) { record = _ref[index]; if (!record.observable) { continue; } if (record.observable.__kb_released) { removals.push(record); continue; } if ((!obj && !record.observable.__kb_null) || (obj && (record.observable.__kb_null || (record.obj !== obj)))) { continue; } else if ((record.creator === creator) || (record.creator.create && (record.creator.create === creator.create))) { if (removals.length) { this.observable_records = _.difference(this.observable_records, removals); return _.indexOf(this.observable_records, record); } else { return index; } } } } if (removals.length) { this.observable_records = _.difference(this.observable_records, removals); } return -1; }; Store.prototype.find = function(obj, creator) { var index; if ((index = this.findIndex(obj, creator)) < 0) { return null; } else { return this.observable_records[index].observable; } }; Store.prototype.isRegistered = function(observable) { var record, _i, _len, _ref; _ref = this.observable_records; for (_i = 0, _len = _ref.length; _i < _len; _i++) { record = _ref[_i]; if (record.observable === observable) { return true; } } return false; }; Store.prototype.findOrCreate = function(obj, options) { var creator, observable; options.store = this; options.creator || (options.creator = kb.utils.inferCreator(obj, options.factory, options.path)); if (!options.creator && (obj instanceof kb.Model)) { options.creator = kb.ViewModel; } creator = options.creator; if (!creator) { return kb.utils.createFromDefaultCreator(obj, options); } else if (creator.models_only) { return obj; } if (creator) { observable = this.find(obj, creator); } if (observable) { return observable; } observable = kb.ignore((function(_this) { return function() { if (creator.create) { observable = creator.create(obj, options); } else { observable = new creator(obj, options); } return observable || ko.observable(null); }; })(this)); if (!ko.isObservable(observable)) { this.isRegistered(observable) || this.register(obj, observable, options); } return observable; }; Store.prototype.findOrReplace = function(obj, creator, observable) { var index, record; obj || kb._throwUnexpected(this, 'obj missing'); if ((index = this.findIndex(obj, creator)) < 0) { return this.register(obj, observable, { creator: creator }); } else { record = this.observable_records[index]; (kb.utils.wrappedObject(record.observable) === obj) || kb._throwUnexpected(this, 'different object'); if (record.observable !== observable) { (record.observable.constructor === observable.constructor) || kb._throwUnexpected(this, 'replacing different type'); this.replaced_observables.push(record.observable); record.observable = observable; } return observable; } }; return Store; })(); /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var kb, ko, _, _argumentsAddKey, _keyArrayToObject, _mergeArray, _mergeObject, _wrappedKey; kb = __webpack_require__(5); _ = kb._; ko = kb.ko; _wrappedKey = kb._wrappedKey = function(obj, key, value) { if (arguments.length === 2) { if (obj && obj.__kb && obj.__kb.hasOwnProperty(key)) { return obj.__kb[key]; } else { return void 0; } } obj || kb._throwUnexpected(this, "no obj for wrapping " + key); obj.__kb || (obj.__kb = {}); obj.__kb[key] = value; return value; }; _argumentsAddKey = function(args, key) { Array.prototype.splice.call(args, 1, 0, key); return args; }; _mergeArray = function(result, key, value) { result[key] || (result[key] = []); if (!_.isArray(value)) { value = [value]; } result[key] = result[key].length ? _.union(result[key], value) : value; return result; }; _mergeObject = function(result, key, value) { result[key] || (result[key] = {}); return _.extend(result[key], value); }; _keyArrayToObject = function(value) { var item, result, _i, _len; result = {}; for (_i = 0, _len = value.length; _i < _len; _i++) { item = value[_i]; result[item] = { key: item }; } return result; }; kb.utils = (function() { function utils() {} utils.wrappedObservable = function(obj, value) { return _wrappedKey.apply(this, _argumentsAddKey(arguments, 'observable')); }; utils.wrappedObject = function(obj, value) { return _wrappedKey.apply(this, _argumentsAddKey(arguments, 'object')); }; utils.wrappedModel = function(obj, value) { if (arguments.length === 1) { value = _wrappedKey(obj, 'object'); if (_.isUndefined(value)) { return obj; } else { return value; } } else { return _wrappedKey(obj, 'object', value); } }; utils.wrappedStore = function(obj, value) { return _wrappedKey.apply(this, _argumentsAddKey(arguments, 'store')); }; utils.wrappedStoreIsOwned = function(obj, value) { return _wrappedKey.apply(this, _argumentsAddKey(arguments, 'store_is_owned')); }; utils.wrappedFactory = function(obj, value) { return _wrappedKey.apply(this, _argumentsAddKey(arguments, 'factory')); }; utils.wrappedEventWatcher = function(obj, value) { return _wrappedKey.apply(this, _argumentsAddKey(arguments, 'event_watcher')); }; utils.wrappedEventWatcherIsOwned = function(obj, value) { return _wrappedKey.apply(this, _argumentsAddKey(arguments, 'event_watcher_is_owned')); }; utils.wrappedDestroy = function(obj) { var __kb; if (!obj.__kb) { return; } if (obj.__kb.event_watcher) { obj.__kb.event_watcher.releaseCallbacks(obj); } __kb = obj.__kb; obj.__kb = null; if (__kb.observable) { __kb.observable.destroy = __kb.observable.release = null; this.wrappedDestroy(__kb.observable); __kb.observable = null; } __kb.factory = null; if (__kb.event_watcher_is_owned) { __kb.event_watcher.destroy(); } __kb.event_watcher = null; if (__kb.store_is_owned) { __kb.store.destroy(); } return __kb.store = null; }; utils.valueType = function(observable) { if (!observable) { return kb.TYPE_UNKNOWN; } if (observable.__kb_is_o) { return observable.valueType(); } if (observable.__kb_is_co || (observable instanceof kb.Collection)) { return kb.TYPE_COLLECTION; } if ((observable instanceof kb.ViewModel) || (observable instanceof kb.Model)) { return kb.TYPE_MODEL; } if (_.isArray(observable)) { return kb.TYPE_ARRAY; } return kb.TYPE_SIMPLE; }; utils.pathJoin = function(path1, path2) { return (path1 ? (path1[path1.length - 1] !== '.' ? "" + path1 + "." : path1) : '') + path2; }; utils.optionsPathJoin = function(options, path) { return _.defaults({ path: this.pathJoin(options.path, path) }, options); }; utils.inferCreator = function(value, factory, path, owner, key) { var creator; if (factory) { creator = factory.creatorForPath(value, path); } if (creator) { return creator; } if (!value) { return null; } if (value instanceof kb.Model) { return kb.ViewModel; } if (value instanceof kb.Collection) { return kb.CollectionObservable; } return null; }; utils.createFromDefaultCreator = function(obj, options) { if (obj instanceof kb.Model) { return kb.viewModel(obj, options); } if (obj instanceof kb.Collection) { return kb.collectionObservable(obj, options); } if (_.isArray(obj)) { return ko.observableArray(obj); } return ko.observable(obj); }; utils.hasModelSignature = function(obj) { return obj && (obj.attributes && !obj.models) && (typeof obj.get === 'function') && (typeof obj.trigger === 'function'); }; utils.hasCollectionSignature = function(obj) { return obj && obj.models && (typeof obj.get === 'function') && (typeof obj.trigger === 'function'); }; utils.collapseOptions = function(options) { var key, result, value, _ref; result = {}; options = { options: options }; while (options.options) { _ref = options.options; for (key in _ref) { value = _ref[key]; switch (key) { case 'internals': case 'requires': case 'excludes': case 'statics': _mergeArray(result, key, value); break; case 'keys': if ((_.isObject(value) && !_.isArray(value)) || (_.isObject(result[key]) && !_.isArray(result[key]))) { if (!_.isObject(value)) { value = [value]; } if (_.isArray(value)) { value = _keyArrayToObject(value); } if (_.isArray(result[key])) { result[key] = _keyArrayToObject(result[key]); } _mergeObject(result, key, value); } else { _mergeArray(result, key, value); } break; case 'factories': if (_.isFunction(value)) { result[key] = value; } else { _mergeObject(result, key, value); } break; case 'static_defaults': _mergeObject(result, key, value); break; case 'options': break; default: result[key] = value; } } options = options.options; } return result; }; utils.unwrapModels = function(obj) { var key, result, value; if (!obj) { return obj; } if (obj.__kb) { if ('object' in obj.__kb) { return obj.__kb.object; } else { return obj; } } else if (_.isArray(obj)) { return _.map(obj, function(test) { return kb.utils.unwrapModels(test); }); } else if (_.isObject(obj) && (obj.constructor === {}.constructor)) { result = {}; for (key in obj) { value = obj[key]; result[key] = kb.utils.unwrapModels(value); } return result; } return obj; }; return utils; })(); /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var kb, ko, _; kb = __webpack_require__(5); _ = kb._; ko = kb.ko; kb.ViewModel = (function() { ViewModel.extend = kb.extend; function ViewModel(model, options, view_model) { return kb.ignore((function(_this) { return function() { var attribute_keys, bb_model, event_watcher, keys, mapped_keys, mapping_info, rel_keys, vm_key, _mdl, _ref; !model || (model instanceof kb.Model) || ((typeof model.get === 'function') && (typeof model.bind === 'function')) || kb._throwUnexpected(_this, 'not a model'); options || (options = {}); view_model || (view_model = {}); if (_.isArray(options)) { options = { keys: options }; } else { options = kb.utils.collapseOptions(options); } _this.__kb || (_this.__kb = {}); _this.__kb.vm_keys = {}; _this.__kb.model_keys = {}; _this.__kb.view_model = _.isUndefined(view_model) ? _this : view_model; !options.internals || (_this.__kb.internals = options.internals); !options.excludes || (_this.__kb.excludes = options.excludes); !options.statics || (_this.__kb.statics = options.statics); !options.static_defaults || (_this.__kb.static_defaults = options.static_defaults); kb.Store.useOptionsOrCreate(options, model, _this); _this.__kb.path = options.path; kb.Factory.useOptionsOrCreate(options, _this, options.path); _mdl = kb._wrappedKey(_this, '_mdl', ko.observable()); _this.model = ko.dependentObservable({ read: function() { _mdl(); return kb.utils.wrappedObject(_this); }, write: function(new_model) { return kb.ignore(function() { var event_watcher, keys, missing, rel_keys; if (kb.utils.wrappedObject(_this) === new_model) { return; } if (_this.__kb_null) { !new_model || kb._throwUnexpected(_this, 'model set on shared null'); return; } kb.utils.wrappedObject(_this, new_model); event_watcher = kb.utils.wrappedEventWatcher(_this); if (!event_watcher) { _mdl(new_model); return; } event_watcher.emitter(new_model); if (!(_this.__kb.keys || !new_model || !new_model.attributes)) { keys = _.keys(new_model.attributes); if (new_model && (rel_keys = kb.orm.keys(new_model))) { keys = _.union(keys, rel_keys); } missing = _.difference(keys, _.keys(_this.__kb.model_keys)); if (missing) { _this.createObservables(new_model, missing); } } _mdl(new_model); }); } }); event_watcher = kb.utils.wrappedEventWatcher(_this, new kb.EventWatcher(model, _this, { emitter: _this.model })); keys = options.requires; if (_this.__kb.internals) { keys = _.union(keys || [], _this.__kb.internals); } if (model && (rel_keys = kb.orm.keys(model))) { keys = _.union(keys || [], rel_keys); } if (options.keys) { if (_.isObject(options.keys) && !_.isArray(options.keys)) { mapped_keys = {}; _ref = options.keys; for (vm_key in _ref) { mapping_info = _ref[vm_key]; mapped_keys[_.isString(mapping_info) ? mapping_info : (mapping_info.key ? mapping_info.key : vm_key)] = true; } _this.__kb.keys = _.keys(mapped_keys); } else { _this.__kb.keys = options.keys; keys = keys ? _.union(keys, _this.__kb.keys) : _.clone(_this.__kb.keys); } } else { bb_model = event_watcher.emitter(); if (bb_model && bb_model.attributes) { attribute_keys = _.keys(bb_model.attributes); keys = keys ? _.union(keys, attribute_keys) : attribute_keys; } } if (keys && _this.__kb.excludes) { keys = _.difference(keys, _this.__kb.excludes); } if (keys && _this.__kb.statics) { keys = _.difference(keys, _this.__kb.statics); } if (_.isObject(options.keys) && !_.isArray(options.keys)) { _this.mapObservables(model, options.keys); } if (_.isObject(options.requires) && !_.isArray(options.requires)) { _this.mapObservables(model, options.requires); } !options.mappings || _this.mapObservables(model, options.mappings); !keys || _this.createObservables(model, keys); !_this.__kb.statics || _this.createObservables(model, _this.__kb.statics, true); !kb.statistics || kb.statistics.register('ViewModel', _this); return _this; }; })(this)); } ViewModel.prototype.destroy = function() { var vm_key; if (this.__kb.view_model !== this) { for (vm_key in this.__kb.vm_keys) { this.__kb.view_model[vm_key] = null; } } this.__kb.view_model = null; kb.releaseKeys(this); kb.utils.wrappedDestroy(this); return !kb.statistics || kb.statistics.unregister('ViewModel', this); }; ViewModel.prototype.shareOptions = function() { return { store: kb.utils.wrappedStore(this), factory: kb.utils.wrappedFactory(this) }; }; ViewModel.prototype.createObservables = function(model, keys, is_static) { var create_options, key, static_defaults, vm_key, _i, _len; if (is_static) { static_defaults = this.__kb.static_defaults || {}; } else { create_options = { store: kb.utils.wrappedStore(this), factory: kb.utils.wrappedFactory(this), path: this.__kb.path, event_watcher: kb.utils.wrappedEventWatcher(this) }; } for (_i = 0, _len = keys.length; _i < _len; _i++) { key = keys[_i]; vm_key = this.__kb.internals && _.contains(this.__kb.internals, key) ? "_" + key : key; if (this[vm_key]) { continue; } this.__kb.vm_keys[vm_key] = this.__kb.model_keys[key] = true; if (is_static) { if (model.has(vm_key)) { this[vm_key] = this.__kb.view_model[vm_key] = model.get(vm_key); } else if (vm_key in static_defaults) { this[vm_key] = this.__kb.view_model[vm_key] = static_defaults[vm_key]; } } else { create_options.key = key; this[vm_key] = this.__kb.view_model[vm_key] = kb.observable(model, create_options, this); } } }; ViewModel.prototype.mapObservables = function(model, mappings) { var create_options, mapping_info, vm_key; create_options = { store: kb.utils.wrappedStore(this), factory: kb.utils.wrappedFactory(this), path: this.__kb.path, event_watcher: kb.utils.wrappedEventWatcher(this) }; for (vm_key in mappings) { mapping_info = mappings[vm_key]; if (this[vm_key]) { continue; } mapping_info = _.isString(mapping_info) ? { key: mapping_info } : _.clone(mapping_info); mapping_info.key || (mapping_info.key = vm_key); this.__kb.vm_keys[vm_key] = this.__kb.model_keys[mapping_info.key] = true; this[vm_key] = this.__kb.view_model[vm_key] = kb.observable(model, _.defaults(mapping_info, create_options), this); } }; return ViewModel; })(); kb.viewModel = function(model, options, view_model) { return new kb.ViewModel(model, options, view_model); }; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var kb, key, _i, _len, _ref; module.exports = kb = __webpack_require__(5); kb.modules = { underscore: kb._, backbone: kb.Parse || kb.Backbone, knockout: kb.ko }; if (typeof window !== "undefined" && window !== null) { _ref = ['_', 'Backbone', 'Parse', 'ko', '$']; for (_i = 0, _len = _ref.length; _i < _len; _i++) { key = _ref[_i]; if (kb[key] && !window.hasOwnProperty(key)) { window[key] = kb[key]; } } } /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var kb, ko, _; kb = __webpack_require__(5); _ = kb._; ko = kb.ko; __webpack_require__(19); module.exports = kb.DefaultObservable = (function() { function DefaultObservable(target_observable, dv) { var observable; this.dv = dv; observable = kb.utils.wrappedObservable(this, ko.dependentObservable({ read: (function(_this) { return function() { var current_target; if ((current_target = ko.utils.unwrapObservable(target_observable()))) { return current_target; } else { return ko.utils.unwrapObservable(_this.dv); } }; })(this), write: function(value) { return target_observable(value); } })); kb.publishMethods(observable, this, ['destroy', 'setToDefault']); return observable; } DefaultObservable.prototype.destroy = function() { return kb.utils.wrappedDestroy(this); }; DefaultObservable.prototype.setToDefault = function() { return kb.utils.wrappedObservable(this)(this.dv); }; return DefaultObservable; })(); kb.defaultObservable = function(target, default_value) { return new kb.DefaultObservable(target, default_value); }; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var arraySlice, kb, ko, _; kb = __webpack_require__(5); _ = kb._; ko = kb.ko; arraySlice = Array.prototype.slice; kb.toFormattedString = function(format) { var arg, args, index, parameter_index, result, value; result = format.slice(); args = arraySlice.call(arguments, 1); for (index in args) { arg = args[index]; value = ko.utils.unwrapObservable(arg); if (_.isUndefined(value) || _.isNull(value)) { value = ''; } parameter_index = format.indexOf("\{" + index + "\}"); while (parameter_index >= 0) { result = result.replace("{" + index + "}", value); parameter_index = format.indexOf("\{" + index + "\}", parameter_index + 1); } } return result; }; kb.parseFormattedString = function(string, format) { var count, format_indices_to_matched_indices, index, match_index, matches, parameter_count, parameter_index, positions, regex, regex_string, result, results, sorted_positions; regex_string = format.slice(); index = 0; parameter_count = 0; positions = {}; while (regex_string.search("\\{" + index + "\\}") >= 0) { parameter_index = format.indexOf("\{" + index + "\}"); while (parameter_index >= 0) { regex_string = regex_string.replace("\{" + index + "\}", '(.*)'); positions[parameter_index] = index; parameter_count++; parameter_index = format.indexOf("\{" + index + "\}", parameter_index + 1); } index++; } count = index; regex = new RegExp(regex_string); matches = regex.exec(string); if (matches) { matches.shift(); } if (!matches || (matches.length !== parameter_count)) { result = []; while (count-- > 0) { result.push(''); } return result; } sorted_positions = _.sortBy(_.keys(positions), function(parameter_index, format_index) { return parseInt(parameter_index, 10); }); format_indices_to_matched_indices = {}; for (match_index in sorted_positions) { parameter_index = sorted_positions[match_index]; index = positions[parameter_index]; if (format_indices_to_matched_indices.hasOwnProperty(index)) { continue; } format_indices_to_matched_indices[index] = match_index; } results = []; index = 0; while (index < count) { results.push(matches[format_indices_to_matched_indices[index]]); index++; } return results; }; module.exports = kb.FormattedObservable = (function() { function FormattedObservable(format, args) { var observable, observable_args; if (_.isArray(args)) { format = format; observable_args = args; } else { observable_args = arraySlice.call(arguments, 1); } observable = kb.utils.wrappedObservable(this, ko.dependentObservable({ read: function() { var arg, _i, _len; args = [ko.utils.unwrapObservable(format)]; for (_i = 0, _len = observable_args.length; _i < _len; _i++) { arg = observable_args[_i]; args.push(ko.utils.unwrapObservable(arg)); } return kb.toFormattedString.apply(null, args); }, write: function(value) { var index, matches, max_count; matches = kb.parseFormattedString(value, ko.utils.unwrapObservable(format)); max_count = Math.min(observable_args.length, matches.length); index = 0; while (index < max_count) { observable_args[index](matches[index]); index++; } } })); return observable; } FormattedObservable.prototype.destroy = function() { return kb.utils.wrappedDestroy(this); }; return FormattedObservable; })(); kb.formattedObservable = function(format, args) { return new kb.FormattedObservable(format, arraySlice.call(arguments, 1)); }; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var kb, ko, _; kb = __webpack_require__(5); _ = kb._; ko = kb.ko; kb.locale_manager || (kb.locale_manager = void 0); module.exports = kb.LocalizedObservable = (function() { LocalizedObservable.extend = kb.extend; function LocalizedObservable(value, options, vm) { var observable; this.value = value; this.vm = vm; options || (options = {}); this.vm || (this.vm = {}); this.read || kb._throwMissing(this, 'read'); kb.locale_manager || kb._throwMissing(this, 'kb.locale_manager'); this.__kb || (this.__kb = {}); this.__kb._onLocaleChange = _.bind(this._onLocaleChange, this); this.__kb._onChange = options.onChange; if (this.value) { value = ko.utils.unwrapObservable(this.value); } this.vo = ko.observable(!value ? null : this.read(value, null)); observable = kb.utils.wrappedObservable(this, ko.dependentObservable({ read: (function(_this) { return function() { if (_this.value) { ko.utils.unwrapObservable(_this.value); } _this.vo(); return _this.read(ko.utils.unwrapObservable(_this.value)); }; })(this), write: (function(_this) { return function(value) { _this.write || kb._throwUnexpected(_this, 'writing to read-only'); _this.write(value, ko.utils.unwrapObservable(_this.value)); _this.vo(value); if (_this.__kb._onChange) { return _this.__kb._onChange(value); } }; })(this), owner: this.vm })); kb.publishMethods(observable, this, ['destroy', 'observedValue', 'resetToCurrent']); kb.locale_manager.bind('change', this.__kb._onLocaleChange); if (options.hasOwnProperty('default')) { observable = kb.DefaultObservable && ko.defaultObservable(observable, options["default"]); } return observable; } LocalizedObservable.prototype.destroy = function() { kb.locale_manager.unbind('change', this.__kb._onLocaleChange); this.vm = null; return kb.utils.wrappedDestroy(this); }; LocalizedObservable.prototype.resetToCurrent = function() { var current_value, observable; observable = kb.utils.wrappedObservable(this); current_value = this.value ? this.read(ko.utils.unwrapObservable(this.value)) : null; if (observable() === current_value) { return; } return observable(current_value); }; LocalizedObservable.prototype.observedValue = function(value) { if (arguments.length === 0) { return this.value; } this.value = value; this._onLocaleChange(); }; LocalizedObservable.prototype._onLocaleChange = function() { var value; value = this.read(ko.utils.unwrapObservable(this.value)); this.vo(value); if (this.__kb._onChange) { return this.__kb._onChange(value); } }; return LocalizedObservable; })(); kb.localizedObservable = function(value, options, view_model) { return new kb.LocalizedObservable(value, options, view_model); }; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var kb, ko, _; kb = __webpack_require__(5); _ = kb._; ko = kb.ko; module.exports = kb.TriggeredObservable = (function() { function TriggeredObservable(emitter, event_selector) { var observable; this.event_selector = event_selector; emitter || kb._throwMissing(this, 'emitter'); this.event_selector || kb._throwMissing(this, 'event_selector'); this.vo = ko.observable(); observable = kb.utils.wrappedObservable(this, ko.dependentObservable((function(_this) { return function() { return _this.vo(); }; })(this))); kb.publishMethods(observable, this, ['destroy']); kb.utils.wrappedEventWatcher(this, new kb.EventWatcher(emitter, this, { emitter: _.bind(this.emitter, this), update: _.bind(this.update, this), event_selector: this.event_selector })); return observable; } TriggeredObservable.prototype.destroy = function() { return kb.utils.wrappedDestroy(this); }; TriggeredObservable.prototype.emitter = function(new_emitter) { if ((arguments.length === 0) || (this.ee === new_emitter)) { return this.ee; } if ((this.ee = new_emitter)) { return this.update(); } }; TriggeredObservable.prototype.update = function() { if (!this.ee) { return; } if (this.vo() !== this.ee) { return this.vo(this.ee); } else { return this.vo.valueHasMutated(); } }; return TriggeredObservable; })(); kb.triggeredObservable = function(emitter, event_selector) { return new kb.TriggeredObservable(emitter, event_selector); }; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var $, callOrGet, kb, ko, _; kb = __webpack_require__(5); _ = kb._; ko = kb.ko; $ = kb.$; __webpack_require__(20); callOrGet = function(value) { value = ko.utils.unwrapObservable(value); if (typeof value === 'function') { return value.apply(null, Array.prototype.slice.call(arguments, 1)); } else { return value; } }; module.exports = kb.Validation = (function() { function Validation() {} return Validation; })(); kb.valueValidator = function(value, bindings, validation_options) { if (validation_options == null) { validation_options = {}; } (validation_options && !(typeof validation_options === 'function')) || (validation_options = {}); return ko.dependentObservable(function() { var active_index, current_value, disabled, identifier, identifier_index, priorities, results, validator; results = { $error_count: 0 }; current_value = ko.utils.unwrapObservable(value); !('disable' in validation_options) || (disabled = callOrGet(validation_options.disable)); !('enable' in validation_options) || (disabled = !callOrGet(validation_options.enable)); priorities = validation_options.priorities || []; _.isArray(priorities) || (priorities = [priorities]); active_index = priorities.length + 1; for (identifier in bindings) { validator = bindings[identifier]; results[identifier] = !disabled && callOrGet(validator, current_value); if (results[identifier]) { results.$error_count++; (identifier_index = _.indexOf(priorities, identifier) >= 0) || (identifier_index = priorities.length); if (results.$active_error && identifier_index < active_index) { results.$active_error = identifier; active_index = identifier_index; } else { results.$active_error || (results.$active_error = identifier, active_index = identifier_index); } } } results.$enabled = !disabled; results.$disable = !!disabled; results.$valid = results.$error_count === 0; return results; }); }; kb.inputValidator = function(view_model, el, validation_options) { var $input_el, bindings, identifier, input_name, options, result, type, validator, validators, _ref; if (validation_options == null) { validation_options = {}; } (validation_options && !(typeof validation_options === 'function')) || (validation_options = {}); validators = kb.valid; $input_el = $(el); if ((input_name = $input_el.attr('name')) && !_.isString(input_name)) { input_name = null; } if (!(bindings = $input_el.attr('data-bind'))) { return null; } options = (new Function("sc", "with(sc[0]) { return { " + bindings + " } }"))([view_model]); if (!(options && options.value)) { return null; } (!options.validation_options) || (_.defaults(options.validation_options, validation_options), validation_options = options.validation_options); bindings = {}; (!validators[type = $input_el.attr('type')]) || (bindings[type] = validators[type]); (!$input_el.attr('required')) || (bindings.required = validators.required); if (options.validations) { _ref = options.validations; for (identifier in _ref) { validator = _ref[identifier]; bindings[identifier] = validator; } } result = kb.valueValidator(options.value, bindings, validation_options); (!input_name && !validation_options.no_attach) || (view_model["$" + input_name] = result); return result; }; kb.formValidator = function(view_model, el) { var $root_el, bindings, form_name, input_el, name, options, results, validation_options, validator, validators, _i, _len, _ref; results = {}; validators = []; $root_el = $(el); if ((form_name = $root_el.attr('name')) && !_.isString(form_name)) { form_name = null; } if ((bindings = $root_el.attr('data-bind'))) { options = (new Function("sc", "with(sc[0]) { return { " + bindings + " } }"))([view_model]); validation_options = options.validation_options; } validation_options || (validation_options = {}); validation_options.no_attach = !!form_name; _ref = $root_el.find('input'); for (_i = 0, _len = _ref.length; _i < _len; _i++) { input_el = _ref[_i]; if (!(name = $(input_el).attr('name'))) { continue; } validator = kb.inputValidator(view_model, input_el, validation_options); !validator || validators.push(results[name] = validator); } results.$error_count = ko.dependentObservable(function() { var error_count, _j, _len1; error_count = 0; for (_j = 0, _len1 = validators.length; _j < _len1; _j++) { validator = validators[_j]; error_count += validator().$error_count; } return error_count; }); results.$valid = ko.dependentObservable(function() { return results.$error_count() === 0; }); results.$enabled = ko.dependentObservable(function() { var enabled, _j, _len1; enabled = true; for (_j = 0, _len1 = validators.length; _j < _len1; _j++) { validator = validators[_j]; enabled &= validator().$enabled; } return enabled; }); results.$disabled = ko.dependentObservable(function() { return !results.$enabled(); }); if (form_name) { view_model["$" + form_name] = results; } return results; }; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { module.exports = __WEBPACK_EXTERNAL_MODULE_18__; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var kb, ko, _; kb = __webpack_require__(5); _ = kb._; ko = kb.ko; kb.Observable.prototype.setToDefault = function() { var _ref; if ((_ref = this.__kb_value) != null) { if (typeof _ref.setToDefault === "function") { _ref.setToDefault(); } } }; kb.ViewModel.prototype.setToDefault = function() { var vm_key, _ref; for (vm_key in this.__kb.vm_keys) { if ((_ref = this[vm_key]) != null) { if (typeof _ref.setToDefault === "function") { _ref.setToDefault(); } } } }; kb.utils.setToDefault = function(obj) { var key, value; if (!obj) { return; } if (ko.isObservable(obj)) { if (typeof obj.setToDefault === "function") { obj.setToDefault(); } } else if (_.isObject(obj)) { for (key in obj) { value = obj[key]; if (value && (ko.isObservable(value) || (typeof value !== 'function')) && ((key[0] !== '_') || key.search('__kb'))) { this.setToDefault(value); } } } return obj; }; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.18.6 Copyright (c) 2011-2014 Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */ var $, EMAIL_REGEXP, NUMBER_REGEXP, URL_REGEXP, kb, ko, _; kb = __webpack_require__(5); _ = kb._; ko = kb.ko; $ = kb.$; URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/; NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; kb.valid = { required: function(value) { return !value; }, url: function(value) { return !URL_REGEXP.test(value); }, email: function(value) { return !EMAIL_REGEXP.test(value); }, number: function(value) { return !NUMBER_REGEXP.test(value); } }; kb.hasChangedFn = function(model) { var attributes, m; m = null; attributes = null; return function() { var current_model; if (m !== (current_model = ko.utils.unwrapObservable(model))) { m = current_model; attributes = (m ? m.toJSON() : null); return false; } if (!(m && attributes)) { return false; } return !_.isEqual(m.toJSON(), attributes); }; }; kb.minLengthFn = function(length) { return function(value) { return !value || value.length < length; }; }; kb.uniqueValueFn = function(model, key, collection) { return function(value) { var c, k, m; m = ko.utils.unwrapObservable(model); k = ko.utils.unwrapObservable(key); c = ko.utils.unwrapObservable(collection); if (!(m && k && c)) { return false; } return !!_.find(c.models, (function(_this) { return function(test) { return (test !== m) && test.get(k) === value; }; })(this)); }; }; kb.untilTrueFn = function(stand_in, fn, model) { var was_true; was_true = false; if (model && ko.isObservable(model)) { model.subscribe(function() { return was_true = false; }); } return function(value) { var f, result; if (!(f = ko.utils.unwrapObservable(fn))) { return ko.utils.unwrapObservable(stand_in); } was_true |= !!(result = f(ko.utils.unwrapObservable(value))); return (was_true ? result : ko.utils.unwrapObservable(stand_in)); }; }; kb.untilFalseFn = function(stand_in, fn, model) { var was_false; was_false = false; if (model && ko.isObservable(model)) { model.subscribe(function() { return was_false = false; }); } return function(value) { var f, result; if (!(f = ko.utils.unwrapObservable(fn))) { return ko.utils.unwrapObservable(stand_in); } was_false |= !(result = f(ko.utils.unwrapObservable(value))); return (was_false ? result : ko.utils.unwrapObservable(stand_in)); }; }; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Backbone.js 1.1.2 // (c) 2010-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Backbone may be freely distributed under the MIT license. // For all details and documentation: // http://backbonejs.org (function(root, factory) { // Set up Backbone appropriately for the environment. Start with AMD. if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(22), __webpack_require__(18), exports], __WEBPACK_AMD_DEFINE_RESULT__ = (function(_, $, exports) { // Export global even in AMD case in case this script is loaded with // others that may still expect a global Backbone. root.Backbone = factory(root, exports, _, $); }.apply(null, __WEBPACK_AMD_DEFINE_ARRAY__)), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); // Next for Node.js or CommonJS. jQuery may not be needed as a module. } else if (typeof exports !== 'undefined') { var _ = require('underscore'); factory(root, exports, _); // Finally, as a browser global. } else { root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$)); } }(this, function(root, Backbone, _, $) { // Initial Setup // ------------- // Save the previous value of the `Backbone` variable, so that it can be // restored later on, if `noConflict` is used. var previousBackbone = root.Backbone; // Create local references to array methods we'll want to use later. var array = []; var push = array.push; var slice = array.slice; var splice = array.splice; // Current version of the library. Keep in sync with `package.json`. Backbone.VERSION = '1.1.2'; // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns // the `$` variable. Backbone.$ = $; // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable // to its previous owner. Returns a reference to this Backbone object. Backbone.noConflict = function() { root.Backbone = previousBackbone; return this; }; // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and // set a `X-Http-Method-Override` header. Backbone.emulateHTTP = false; // Turn on `emulateJSON` to support legacy servers that can't deal with direct // `application/json` requests ... will encode the body as // `application/x-www-form-urlencoded` instead and will send the model in a // form param named `model`. Backbone.emulateJSON = false; // Backbone.Events // --------------- // A module that can be mixed in to *any object* in order to provide it with // custom events. You may bind with `on` or remove with `off` callback // functions to an event; `trigger`-ing an event fires all callbacks in // succession. // // var object = {}; // _.extend(object, Backbone.Events); // object.on('expand', function(){ alert('expanded'); }); // object.trigger('expand'); // var Events = Backbone.Events = { // Bind an event to a `callback` function. Passing `"all"` will bind // the callback to all events fired. on: function(name, callback, context) { if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({callback: callback, context: context, ctx: context || this}); return this; }, // Bind an event to only be triggered a single time. After the first time // the callback is invoked, it will be removed. once: function(name, callback, context) { if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function() { self.off(name, once); callback.apply(this, arguments); }); once._callback = callback; return this.on(name, once, context); }, // Remove one or many callbacks. If `context` is null, removes all // callbacks with that function. If `callback` is null, removes all // callbacks for the event. If `name` is null, removes all bound // callbacks for all events. off: function(name, callback, context) { var retain, ev, events, names, i, l, j, k; if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; if (!name && !callback && !context) { this._events = void 0; return this; } names = name ? [name] : _.keys(this._events); for (i = 0, l = names.length; i < l; i++) { name = names[i]; if (events = this._events[name]) { this._events[name] = retain = []; if (callback || context) { for (j = 0, k = events.length; j < k; j++) { ev = events[j]; if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) { retain.push(ev); } } } if (!retain.length) delete this._events[name]; } } return this; }, // Trigger one or many events, firing all bound callbacks. Callbacks are // passed the same arguments as `trigger` is, apart from the event name // (unless you're listening on `"all"`, which will cause your callback to // receive the true name of the event as the first argument). trigger: function(name) { if (!this._events) return this; var args = slice.call(arguments, 1); if (!eventsApi(this, 'trigger', name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); if (allEvents) triggerEvents(allEvents, arguments); return this; }, // Tell this object to stop listening to either specific events ... or // to every object it's currently listening to. stopListening: function(obj, name, callback) { var listeningTo = this._listeningTo; if (!listeningTo) return this; var remove = !name && !callback; if (!callback && typeof name === 'object') callback = this; if (obj) (listeningTo = {})[obj._listenId] = obj; for (var id in listeningTo) { obj = listeningTo[id]; obj.off(name, callback, this); if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id]; } return this; } }; // Regular expression used to split event strings. var eventSplitter = /\s+/; // Implement fancy features of the Events API such as multiple event // names `"change blur"` and jQuery-style event maps `{change: action}` // in terms of the existing API. var eventsApi = function(obj, action, name, rest) { if (!name) return true; // Handle event maps. if (typeof name === 'object') { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } return false; } // Handle space separated event names. if (eventSplitter.test(name)) { var names = name.split(eventSplitter); for (var i = 0, l = names.length; i < l; i++) { obj[action].apply(obj, [names[i]].concat(rest)); } return false; } return true; }; // A difficult-to-believe, but optimized internal dispatch function for // triggering events. Tries to keep the usual cases speedy (most internal // Backbone events have 3 arguments). var triggerEvents = function(events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; } }; var listenMethods = {listenTo: 'on', listenToOnce: 'once'}; // Inversion-of-control versions of `on` and `once`. Tell *this* object to // listen to an event in another object ... keeping track of what it's // listening to. _.each(listenMethods, function(implementation, method) { Events[method] = function(obj, name, callback) { var listeningTo = this._listeningTo || (this._listeningTo = {}); var id = obj._listenId || (obj._listenId = _.uniqueId('l')); listeningTo[id] = obj; if (!callback && typeof name === 'object') callback = this; obj[implementation](name, callback, this); return this; }; }); // Aliases for backwards compatibility. Events.bind = Events.on; Events.unbind = Events.off; // Allow the `Backbone` object to serve as a global event bus, for folks who // want global "pubsub" in a convenient place. _.extend(Backbone, Events); // Backbone.Model // -------------- // Backbone **Models** are the basic data object in the framework -- // frequently representing a row in a table in a database on your server. // A discrete chunk of data and a bunch of useful, related methods for // performing computations and transformations on that data. // Create a new model with the specified attributes. A client id (`cid`) // is automatically generated and assigned for you. var Model = Backbone.Model = function(attributes, options) { var attrs = attributes || {}; options || (options = {}); this.cid = _.uniqueId('c'); this.attributes = {}; if (options.collection) this.collection = options.collection; if (options.parse) attrs = this.parse(attrs, options) || {}; attrs = _.defaults({}, attrs, _.result(this, 'defaults')); this.set(attrs, options); this.changed = {}; this.initialize.apply(this, arguments); }; // Attach all inheritable methods to the Model prototype. _.extend(Model.prototype, Events, { // A hash of attributes whose current and previous value differ. changed: null, // The value returned during the last failed validation. validationError: null, // The default name for the JSON `id` attribute is `"id"`. MongoDB and // CouchDB users may want to set this to `"_id"`. idAttribute: 'id', // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Return a copy of the model's `attributes` object. toJSON: function(options) { return _.clone(this.attributes); }, // Proxy `Backbone.sync` by default -- but override this if you need // custom syncing semantics for *this* particular model. sync: function() { return Backbone.sync.apply(this, arguments); }, // Get the value of an attribute. get: function(attr) { return this.attributes[attr]; }, // Get the HTML-escaped value of an attribute. escape: function(attr) { return _.escape(this.get(attr)); }, // Returns `true` if the attribute contains a value that is not null // or undefined. has: function(attr) { return this.get(attr) != null; }, // Set a hash of model attributes on the object, firing `"change"`. This is // the core primitive operation of a model, updating the data and notifying // anyone who needs to know about the change in state. The heart of the beast. set: function(key, val, options) { var attr, attrs, unset, changes, silent, changing, prev, current; if (key == null) return this; // Handle both `"key", value` and `{key: value}` -style arguments. if (typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options || (options = {}); // Run validation. if (!this._validate(attrs, options)) return false; // Extract attributes and options. unset = options.unset; silent = options.silent; changes = []; changing = this._changing; this._changing = true; if (!changing) { this._previousAttributes = _.clone(this.attributes); this.changed = {}; } current = this.attributes, prev = this._previousAttributes; // Check for changes of `id`. if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; // For each `set` attribute, update or delete the current value. for (attr in attrs) { val = attrs[attr]; if (!_.isEqual(current[attr], val)) changes.push(attr); if (!_.isEqual(prev[attr], val)) { this.changed[attr] = val; } else { delete this.changed[attr]; } unset ? delete current[attr] : current[attr] = val; } // Trigger all relevant attribute changes. if (!silent) { if (changes.length) this._pending = options; for (var i = 0, l = changes.length; i < l; i++) { this.trigger('change:' + changes[i], this, current[changes[i]], options); } } // You might be wondering why there's a `while` loop here. Changes can // be recursively nested within `"change"` events. if (changing) return this; if (!silent) { while (this._pending) { options = this._pending; this._pending = false; this.trigger('change', this, options); } } this._pending = false; this._changing = false; return this; }, // Remove an attribute from the model, firing `"change"`. `unset` is a noop // if the attribute doesn't exist. unset: function(attr, options) { return this.set(attr, void 0, _.extend({}, options, {unset: true})); }, // Clear all attributes on the model, firing `"change"`. clear: function(options) { var attrs = {}; for (var key in this.attributes) attrs[key] = void 0; return this.set(attrs, _.extend({}, options, {unset: true})); }, // Determine if the model has changed since the last `"change"` event. // If you specify an attribute name, determine if that attribute has changed. hasChanged: function(attr) { if (attr == null) return !_.isEmpty(this.changed); return _.has(this.changed, attr); }, // Return an object containing all the attributes that have changed, or // false if there are no changed attributes. Useful for determining what // parts of a view need to be updated and/or what attributes need to be // persisted to the server. Unset attributes will be set to undefined. // You can also pass an attributes object to diff against the model, // determining if there *would be* a change. changedAttributes: function(diff) { if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; var val, changed = false; var old = this._changing ? this._previousAttributes : this.attributes; for (var attr in diff) { if (_.isEqual(old[attr], (val = diff[attr]))) continue; (changed || (changed = {}))[attr] = val; } return changed; }, // Get the previous value of an attribute, recorded at the time the last // `"change"` event was fired. previous: function(attr) { if (attr == null || !this._previousAttributes) return null; return this._previousAttributes[attr]; }, // Get all of the attributes of the model at the time of the previous // `"change"` event. previousAttributes: function() { return _.clone(this._previousAttributes); }, // Fetch the model from the server. If the server's representation of the // model differs from its current attributes, they will be overridden, // triggering a `"change"` event. fetch: function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { if (!model.set(model.parse(resp, options), options)) return false; if (success) success(model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Set a hash of model attributes, and sync the model to the server. // If the server returns an attributes hash that differs, the model's // state will be `set` again. save: function(key, val, options) { var attrs, method, xhr, attributes = this.attributes; // Handle both `"key", value` and `{key: value}` -style arguments. if (key == null || typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options = _.extend({validate: true}, options); // If we're not waiting and attributes exist, save acts as // `set(attr).save(null, opts)` with validation. Otherwise, check if // the model will be valid when the attributes, if any, are set. if (attrs && !options.wait) { if (!this.set(attrs, options)) return false; } else { if (!this._validate(attrs, options)) return false; } // Set temporary attributes if `{wait: true}`. if (attrs && options.wait) { this.attributes = _.extend({}, attributes, attrs); } // After a successful server-side save, the client is (optionally) // updated with the server-side state. if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { // Ensure attributes are restored during synchronous saves. model.attributes = attributes; var serverAttrs = model.parse(resp, options); if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) { return false; } if (success) success(model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); if (method === 'patch') options.attrs = attrs; xhr = this.sync(method, this, options); // Restore attributes. if (attrs && options.wait) this.attributes = attributes; return xhr; }, // Destroy this model on the server if it was already persisted. // Optimistically removes the model from its collection, if it has one. // If `wait: true` is passed, waits for the server to respond before removal. destroy: function(options) { options = options ? _.clone(options) : {}; var model = this; var success = options.success; var destroy = function() { model.trigger('destroy', model, model.collection, options); }; options.success = function(resp) { if (options.wait || model.isNew()) destroy(); if (success) success(model, resp, options); if (!model.isNew()) model.trigger('sync', model, resp, options); }; if (this.isNew()) { options.success(); return false; } wrapError(this, options); var xhr = this.sync('delete', this, options); if (!options.wait) destroy(); return xhr; }, // Default URL for the model's representation on the server -- if you're // using Backbone's restful methods, override this to change the endpoint // that will be called. url: function() { var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); if (this.isNew()) return base; return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id); }, // **parse** converts a response into the hash of attributes to be `set` on // the model. The default implementation is just to pass the response along. parse: function(resp, options) { return resp; }, // Create a new model with identical attributes to this one. clone: function() { return new this.constructor(this.attributes); }, // A model is new if it has never been saved to the server, and lacks an id. isNew: function() { return !this.has(this.idAttribute); }, // Check if the model is currently in a valid state. isValid: function(options) { return this._validate({}, _.extend(options || {}, { validate: true })); }, // Run validation against the next complete set of model attributes, // returning `true` if all is well. Otherwise, fire an `"invalid"` event. _validate: function(attrs, options) { if (!options.validate || !this.validate) return true; attrs = _.extend({}, this.attributes, attrs); var error = this.validationError = this.validate(attrs, options) || null; if (!error) return true; this.trigger('invalid', this, error, _.extend(options, {validationError: error})); return false; } }); // Underscore methods that we want to implement on the Model. var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit']; // Mix in each Underscore method as a proxy to `Model#attributes`. _.each(modelMethods, function(method) { Model.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.attributes); return _[method].apply(_, args); }; }); // Backbone.Collection // ------------------- // If models tend to represent a single row of data, a Backbone Collection is // more analagous to a table full of data ... or a small slice or page of that // table, or a collection of rows that belong together for a particular reason // -- all of the messages in this particular folder, all of the documents // belonging to this particular author, and so on. Collections maintain // indexes of their models, both in order, and for lookup by `id`. // Create a new **Collection**, perhaps to contain a specific type of `model`. // If a `comparator` is specified, the Collection will maintain // its models in sort order, as they're added and removed. var Collection = Backbone.Collection = function(models, options) { options || (options = {}); if (options.model) this.model = options.model; if (options.comparator !== void 0) this.comparator = options.comparator; this._reset(); this.initialize.apply(this, arguments); if (models) this.reset(models, _.extend({silent: true}, options)); }; // Default options for `Collection#set`. var setOptions = {add: true, remove: true, merge: true}; var addOptions = {add: true, remove: false}; // Define the Collection's inheritable methods. _.extend(Collection.prototype, Events, { // The default model for a collection is just a **Backbone.Model**. // This should be overridden in most cases. model: Model, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // The JSON representation of a Collection is an array of the // models' attributes. toJSON: function(options) { return this.map(function(model){ return model.toJSON(options); }); }, // Proxy `Backbone.sync` by default. sync: function() { return Backbone.sync.apply(this, arguments); }, // Add a model, or list of models to the set. add: function(models, options) { return this.set(models, _.extend({merge: false}, options, addOptions)); }, // Remove a model, or a list of models from the set. remove: function(models, options) { var singular = !_.isArray(models); models = singular ? [models] : _.clone(models); options || (options = {}); var i, l, index, model; for (i = 0, l = models.length; i < l; i++) { model = models[i] = this.get(models[i]); if (!model) continue; delete this._byId[model.id]; delete this._byId[model.cid]; index = this.indexOf(model); this.models.splice(index, 1); this.length--; if (!options.silent) { options.index = index; model.trigger('remove', model, this, options); } this._removeReference(model, options); } return singular ? models[0] : models; }, // Update a collection by `set`-ing a new list of models, adding new ones, // removing models that are no longer present, and merging models that // already exist in the collection, as necessary. Similar to **Model#set**, // the core operation for updating the data contained by the collection. set: function(models, options) { options = _.defaults({}, options, setOptions); if (options.parse) models = this.parse(models, options); var singular = !_.isArray(models); models = singular ? (models ? [models] : []) : _.clone(models); var i, l, id, model, attrs, existing, sort; var at = options.at; var targetModel = this.model; var sortable = this.comparator && (at == null) && options.sort !== false; var sortAttr = _.isString(this.comparator) ? this.comparator : null; var toAdd = [], toRemove = [], modelMap = {}; var add = options.add, merge = options.merge, remove = options.remove; var order = !sortable && add && remove ? [] : false; // Turn bare objects into model references, and prevent invalid models // from being added. for (i = 0, l = models.length; i < l; i++) { attrs = models[i] || {}; if (attrs instanceof Model) { id = model = attrs; } else { id = attrs[targetModel.prototype.idAttribute || 'id']; } // If a duplicate is found, prevent it from being added and // optionally merge it into the existing model. if (existing = this.get(id)) { if (remove) modelMap[existing.cid] = true; if (merge) { attrs = attrs === model ? model.attributes : attrs; if (options.parse) attrs = existing.parse(attrs, options); existing.set(attrs, options); if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; } models[i] = existing; // If this is a new, valid model, push it to the `toAdd` list. } else if (add) { model = models[i] = this._prepareModel(attrs, options); if (!model) continue; toAdd.push(model); this._addReference(model, options); } // Do not add multiple models with the same `id`. model = existing || model; if (order && (model.isNew() || !modelMap[model.id])) order.push(model); modelMap[model.id] = true; } // Remove nonexistent models if appropriate. if (remove) { for (i = 0, l = this.length; i < l; ++i) { if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model); } if (toRemove.length) this.remove(toRemove, options); } // See if sorting is needed, update `length` and splice in new models. if (toAdd.length || (order && order.length)) { if (sortable) sort = true; this.length += toAdd.length; if (at != null) { for (i = 0, l = toAdd.length; i < l; i++) { this.models.splice(at + i, 0, toAdd[i]); } } else { if (order) this.models.length = 0; var orderedModels = order || toAdd; for (i = 0, l = orderedModels.length; i < l; i++) { this.models.push(orderedModels[i]); } } } // Silently sort the collection if appropriate. if (sort) this.sort({silent: true}); // Unless silenced, it's time to fire all appropriate add/sort events. if (!options.silent) { for (i = 0, l = toAdd.length; i < l; i++) { (model = toAdd[i]).trigger('add', model, this, options); } if (sort || (order && order.length)) this.trigger('sort', this, options); } // Return the added (or merged) model (or models). return singular ? models[0] : models; }, // When you have more items than you want to add or remove individually, // you can reset the entire set with a new list of models, without firing // any granular `add` or `remove` events. Fires `reset` when finished. // Useful for bulk operations and optimizations. reset: function(models, options) { options || (options = {}); for (var i = 0, l = this.models.length; i < l; i++) { this._removeReference(this.models[i], options); } options.previousModels = this.models; this._reset(); models = this.add(models, _.extend({silent: true}, options)); if (!options.silent) this.trigger('reset', this, options); return models; }, // Add a model to the end of the collection. push: function(model, options) { return this.add(model, _.extend({at: this.length}, options)); }, // Remove a model from the end of the collection. pop: function(options) { var model = this.at(this.length - 1); this.remove(model, options); return model; }, // Add a model to the beginning of the collection. unshift: function(model, options) { return this.add(model, _.extend({at: 0}, options)); }, // Remove a model from the beginning of the collection. shift: function(options) { var model = this.at(0); this.remove(model, options); return model; }, // Slice out a sub-array of models from the collection. slice: function() { return slice.apply(this.models, arguments); }, // Get a model from the set by id. get: function(obj) { if (obj == null) return void 0; return this._byId[obj] || this._byId[obj.id] || this._byId[obj.cid]; }, // Get the model at the given index. at: function(index) { return this.models[index]; }, // Return models with matching attributes. Useful for simple cases of // `filter`. where: function(attrs, first) { if (_.isEmpty(attrs)) return first ? void 0 : []; return this[first ? 'find' : 'filter'](function(model) { for (var key in attrs) { if (attrs[key] !== model.get(key)) return false; } return true; }); }, // Return the first model with matching attributes. Useful for simple cases // of `find`. findWhere: function(attrs) { return this.where(attrs, true); }, // Force the collection to re-sort itself. You don't need to call this under // normal circumstances, as the set will maintain sort order as each item // is added. sort: function(options) { if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); options || (options = {}); // Run sort based on type of `comparator`. if (_.isString(this.comparator) || this.comparator.length === 1) { this.models = this.sortBy(this.comparator, this); } else { this.models.sort(_.bind(this.comparator, this)); } if (!options.silent) this.trigger('sort', this, options); return this; }, // Pluck an attribute from each model in the collection. pluck: function(attr) { return _.invoke(this.models, 'get', attr); }, // Fetch the default set of models for this collection, resetting the // collection when they arrive. If `reset: true` is passed, the response // data will be passed through the `reset` method instead of `set`. fetch: function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var success = options.success; var collection = this; options.success = function(resp) { var method = options.reset ? 'reset' : 'set'; collection[method](resp, options); if (success) success(collection, resp, options); collection.trigger('sync', collection, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Create a new instance of a model in this collection. Add the model to the // collection immediately, unless `wait: true` is passed, in which case we // wait for the server to agree. create: function(model, options) { options = options ? _.clone(options) : {}; if (!(model = this._prepareModel(model, options))) return false; if (!options.wait) this.add(model, options); var collection = this; var success = options.success; options.success = function(model, resp) { if (options.wait) collection.add(model, options); if (success) success(model, resp, options); }; model.save(null, options); return model; }, // **parse** converts a response into a list of models to be added to the // collection. The default implementation is just to pass it through. parse: function(resp, options) { return resp; }, // Create a new collection with an identical list of models as this one. clone: function() { return new this.constructor(this.models); }, // Private method to reset all internal state. Called when the collection // is first initialized or reset. _reset: function() { this.length = 0; this.models = []; this._byId = {}; }, // Prepare a hash of attributes (or other model) to be added to this // collection. _prepareModel: function(attrs, options) { if (attrs instanceof Model) return attrs; options = options ? _.clone(options) : {}; options.collection = this; var model = new this.model(attrs, options); if (!model.validationError) return model; this.trigger('invalid', this, model.validationError, options); return false; }, // Internal method to create a model's ties to a collection. _addReference: function(model, options) { this._byId[model.cid] = model; if (model.id != null) this._byId[model.id] = model; if (!model.collection) model.collection = this; model.on('all', this._onModelEvent, this); }, // Internal method to sever a model's ties to a collection. _removeReference: function(model, options) { if (this === model.collection) delete model.collection; model.off('all', this._onModelEvent, this); }, // Internal method called every time a model in the set fires an event. // Sets need to update their indexes when models change ids. All other // events simply proxy through. "add" and "remove" events that originate // in other collections are ignored. _onModelEvent: function(event, model, collection, options) { if ((event === 'add' || event === 'remove') && collection !== this) return; if (event === 'destroy') this.remove(model, options); if (model && event === 'change:' + model.idAttribute) { delete this._byId[model.previous(model.idAttribute)]; if (model.id != null) this._byId[model.id] = model; } this.trigger.apply(this, arguments); } }); // Underscore methods that we want to implement on the Collection. // 90% of the core usefulness of Backbone Collections is actually implemented // right here: var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl', 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', 'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle', 'lastIndexOf', 'isEmpty', 'chain', 'sample']; // Mix in each Underscore method as a proxy to `Collection#models`. _.each(methods, function(method) { Collection.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.models); return _[method].apply(_, args); }; }); // Underscore methods that take a property name as an argument. var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy']; // Use attributes instead of properties. _.each(attributeMethods, function(method) { Collection.prototype[method] = function(value, context) { var iterator = _.isFunction(value) ? value : function(model) { return model.get(value); }; return _[method](this.models, iterator, context); }; }); // Backbone.View // ------------- // Backbone Views are almost more convention than they are actual code. A View // is simply a JavaScript object that represents a logical chunk of UI in the // DOM. This might be a single item, an entire list, a sidebar or panel, or // even the surrounding frame which wraps your whole app. Defining a chunk of // UI as a **View** allows you to define your DOM events declaratively, without // having to worry about render order ... and makes it easy for the view to // react to specific changes in the state of your models. // Creating a Backbone.View creates its initial element outside of the DOM, // if an existing element is not provided... var View = Backbone.View = function(options) { this.cid = _.uniqueId('view'); options || (options = {}); _.extend(this, _.pick(options, viewOptions)); this._ensureElement(); this.initialize.apply(this, arguments); this.delegateEvents(); }; // Cached regex to split keys for `delegate`. var delegateEventSplitter = /^(\S+)\s*(.*)$/; // List of view options to be merged as properties. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; // Set up all inheritable **Backbone.View** properties and methods. _.extend(View.prototype, Events, { // The default `tagName` of a View's element is `"div"`. tagName: 'div', // jQuery delegate for element lookup, scoped to DOM elements within the // current view. This should be preferred to global lookups where possible. $: function(selector) { return this.$el.find(selector); }, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // **render** is the core function that your view should override, in order // to populate its element (`this.el`), with the appropriate HTML. The // convention is for **render** to always return `this`. render: function() { return this; }, // Remove this view by taking the element out of the DOM, and removing any // applicable Backbone.Events listeners. remove: function() { this.$el.remove(); this.stopListening(); return this; }, // Change the view's element (`this.el` property), including event // re-delegation. setElement: function(element, delegate) { if (this.$el) this.undelegateEvents(); this.$el = element instanceof Backbone.$ ? element : Backbone.$(element); this.el = this.$el[0]; if (delegate !== false) this.delegateEvents(); return this; }, // Set callbacks, where `this.events` is a hash of // // *{"event selector": "callback"}* // // { // 'mousedown .title': 'edit', // 'click .button': 'save', // 'click .open': function(e) { ... } // } // // pairs. Callbacks will be bound to the view, with `this` set properly. // Uses event delegation for efficiency. // Omitting the selector binds the event to `this.el`. // This only works for delegate-able events: not `focus`, `blur`, and // not `change`, `submit`, and `reset` in Internet Explorer. delegateEvents: function(events) { if (!(events || (events = _.result(this, 'events')))) return this; this.undelegateEvents(); for (var key in events) { var method = events[key]; if (!_.isFunction(method)) method = this[events[key]]; if (!method) continue; var match = key.match(delegateEventSplitter); var eventName = match[1], selector = match[2]; method = _.bind(method, this); eventName += '.delegateEvents' + this.cid; if (selector === '') { this.$el.on(eventName, method); } else { this.$el.on(eventName, selector, method); } } return this; }, // Clears all callbacks previously bound to the view with `delegateEvents`. // You usually don't need to use this, but may wish to if you have multiple // Backbone views attached to the same DOM element. undelegateEvents: function() { this.$el.off('.delegateEvents' + this.cid); return this; }, // Ensure that the View has a DOM element to render into. // If `this.el` is a string, pass it through `$()`, take the first // matching element, and re-assign it to `el`. Otherwise, create // an element from the `id`, `className` and `tagName` properties. _ensureElement: function() { if (!this.el) { var attrs = _.extend({}, _.result(this, 'attributes')); if (this.id) attrs.id = _.result(this, 'id'); if (this.className) attrs['class'] = _.result(this, 'className'); var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs); this.setElement($el, false); } else { this.setElement(_.result(this, 'el'), false); } } }); // Backbone.sync // ------------- // Override this function to change the manner in which Backbone persists // models to the server. You will be passed the type of request, and the // model in question. By default, makes a RESTful Ajax request // to the model's `url()`. Some possible customizations could be: // // * Use `setTimeout` to batch rapid-fire updates into a single request. // * Send up the models as XML instead of JSON. // * Persist models via WebSockets instead of Ajax. // // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests // as `POST`, with a `_method` parameter containing the true HTTP method, // as well as all requests with the body as `application/x-www-form-urlencoded` // instead of `application/json` with the model in a param named `model`. // Useful when interfacing with server-side languages like **PHP** that make // it difficult to read the body of `PUT` requests. Backbone.sync = function(method, model, options) { var type = methodMap[method]; // Default options, unless specified. _.defaults(options || (options = {}), { emulateHTTP: Backbone.emulateHTTP, emulateJSON: Backbone.emulateJSON }); // Default JSON-request options. var params = {type: type, dataType: 'json'}; // Ensure that we have a URL. if (!options.url) { params.url = _.result(model, 'url') || urlError(); } // Ensure that we have the appropriate request data. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { params.contentType = 'application/json'; params.data = JSON.stringify(options.attrs || model.toJSON(options)); } // For older servers, emulate JSON by encoding the request into an HTML-form. if (options.emulateJSON) { params.contentType = 'application/x-www-form-urlencoded'; params.data = params.data ? {model: params.data} : {}; } // For older servers, emulate HTTP by mimicking the HTTP method with `_method` // And an `X-HTTP-Method-Override` header. if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { params.type = 'POST'; if (options.emulateJSON) params.data._method = type; var beforeSend = options.beforeSend; options.beforeSend = function(xhr) { xhr.setRequestHeader('X-HTTP-Method-Override', type); if (beforeSend) return beforeSend.apply(this, arguments); }; } // Don't process data on a non-GET request. if (params.type !== 'GET' && !options.emulateJSON) { params.processData = false; } // If we're sending a `PATCH` request, and we're in an old Internet Explorer // that still has ActiveX enabled by default, override jQuery to use that // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. if (params.type === 'PATCH' && noXhrPatch) { params.xhr = function() { return new ActiveXObject("Microsoft.XMLHTTP"); }; } // Make the request, allowing the user to override any Ajax options. var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); model.trigger('request', model, xhr, options); return xhr; }; var noXhrPatch = typeof window !== 'undefined' && !!window.ActiveXObject && !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent); // Map from CRUD to HTTP for our default `Backbone.sync` implementation. var methodMap = { 'create': 'POST', 'update': 'PUT', 'patch': 'PATCH', 'delete': 'DELETE', 'read': 'GET' }; // Set the default implementation of `Backbone.ajax` to proxy through to `$`. // Override this if you'd like to use a different library. Backbone.ajax = function() { return Backbone.$.ajax.apply(Backbone.$, arguments); }; // Backbone.Router // --------------- // Routers map faux-URLs to actions, and fire events when routes are // matched. Creating a new one sets its `routes` hash, if not set statically. var Router = Backbone.Router = function(options) { options || (options = {}); if (options.routes) this.routes = options.routes; this._bindRoutes(); this.initialize.apply(this, arguments); }; // Cached regular expressions for matching named param parts and splatted // parts of route strings. var optionalParam = /\((.*?)\)/g; var namedParam = /(\(\?)?:\w+/g; var splatParam = /\*\w+/g; var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; // Set up all inheritable **Backbone.Router** properties and methods. _.extend(Router.prototype, Events, { // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Manually bind a single named route to a callback. For example: // // this.route('search/:query/p:num', 'search', function(query, num) { // ... // }); // route: function(route, name, callback) { if (!_.isRegExp(route)) route = this._routeToRegExp(route); if (_.isFunction(name)) { callback = name; name = ''; } if (!callback) callback = this[name]; var router = this; Backbone.history.route(route, function(fragment) { var args = router._extractParameters(route, fragment); router.execute(callback, args); router.trigger.apply(router, ['route:' + name].concat(args)); router.trigger('route', name, args); Backbone.history.trigger('route', router, name, args); }); return this; }, // Execute a route handler with the provided parameters. This is an // excellent place to do pre-route setup or post-route cleanup. execute: function(callback, args) { if (callback) callback.apply(this, args); }, // Simple proxy to `Backbone.history` to save a fragment into the history. navigate: function(fragment, options) { Backbone.history.navigate(fragment, options); return this; }, // Bind all defined routes to `Backbone.history`. We have to reverse the // order of the routes here to support behavior where the most general // routes can be defined at the bottom of the route map. _bindRoutes: function() { if (!this.routes) return; this.routes = _.result(this, 'routes'); var route, routes = _.keys(this.routes); while ((route = routes.pop()) != null) { this.route(route, this.routes[route]); } }, // Convert a route string into a regular expression, suitable for matching // against the current location hash. _routeToRegExp: function(route) { route = route.replace(escapeRegExp, '\\$&') .replace(optionalParam, '(?:$1)?') .replace(namedParam, function(match, optional) { return optional ? match : '([^/?]+)'; }) .replace(splatParam, '([^?]*?)'); return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); }, // Given a route, and a URL fragment that it matches, return the array of // extracted decoded parameters. Empty or unmatched parameters will be // treated as `null` to normalize cross-browser behavior. _extractParameters: function(route, fragment) { var params = route.exec(fragment).slice(1); return _.map(params, function(param, i) { // Don't decode the search params. if (i === params.length - 1) return param || null; return param ? decodeURIComponent(param) : null; }); } }); // Backbone.History // ---------------- // Handles cross-browser history management, based on either // [pushState](http://diveintohtml5.info/history.html) and real URLs, or // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) // and URL fragments. If the browser supports neither (old IE, natch), // falls back to polling. var History = Backbone.History = function() { this.handlers = []; _.bindAll(this, 'checkUrl'); // Ensure that `History` can be used outside of the browser. if (typeof window !== 'undefined') { this.location = window.location; this.history = window.history; } }; // Cached regex for stripping a leading hash/slash and trailing space. var routeStripper = /^[#\/]|\s+$/g; // Cached regex for stripping leading and trailing slashes. var rootStripper = /^\/+|\/+$/g; // Cached regex for detecting MSIE. var isExplorer = /msie [\w.]+/; // Cached regex for removing a trailing slash. var trailingSlash = /\/$/; // Cached regex for stripping urls of hash. var pathStripper = /#.*$/; // Has the history handling already been started? History.started = false; // Set up all inheritable **Backbone.History** properties and methods. _.extend(History.prototype, Events, { // The default interval to poll for hash changes, if necessary, is // twenty times a second. interval: 50, // Are we at the app root? atRoot: function() { return this.location.pathname.replace(/[^\/]$/, '$&/') === this.root; }, // Gets the true hash value. Cannot use location.hash directly due to bug // in Firefox where location.hash will always be decoded. getHash: function(window) { var match = (window || this).location.href.match(/#(.*)$/); return match ? match[1] : ''; }, // Get the cross-browser normalized URL fragment, either from the URL, // the hash, or the override. getFragment: function(fragment, forcePushState) { if (fragment == null) { if (this._hasPushState || !this._wantsHashChange || forcePushState) { fragment = decodeURI(this.location.pathname + this.location.search); var root = this.root.replace(trailingSlash, ''); if (!fragment.indexOf(root)) fragment = fragment.slice(root.length); } else { fragment = this.getHash(); } } return fragment.replace(routeStripper, ''); }, // Start the hash change handling, returning `true` if the current URL matches // an existing route, and `false` otherwise. start: function(options) { if (History.started) throw new Error("Backbone.history has already been started"); History.started = true; // Figure out the initial configuration. Do we need an iframe? // Is pushState desired ... is it available? this.options = _.extend({root: '/'}, this.options, options); this.root = this.options.root; this._wantsHashChange = this.options.hashChange !== false; this._wantsPushState = !!this.options.pushState; this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); var fragment = this.getFragment(); var docMode = document.documentMode; var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); // Normalize root to always include a leading and trailing slash. this.root = ('/' + this.root + '/').replace(rootStripper, '/'); if (oldIE && this._wantsHashChange) { var frame = Backbone.$('