/* knockback-core-stack.js 0.19.4 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_15__) { 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__(12); __webpack_require__(13); module.exports = __webpack_require__(14); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.19.4 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, KEYS_PUBLISH, kb, ko, _, _ref, __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; }; _ref = kb = __webpack_require__(6), _ = _ref._, ko = _ref.ko; COMPARE_EQUAL = 0; COMPARE_ASCENDING = -1; COMPARE_DESCENDING = 1; KEYS_PUBLISH = ['destroy', 'shareOptions', 'filters', 'comparator', 'sortAttribute', 'viewModelByModel', 'hasViewModels']; 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) { this._onCollectionChange = __bind(this._onCollectionChange, this); return kb.ignore((function(_this) { return function() { var create_options, observable, _ref1; if (_.isUndefined(options) && !(collection instanceof kb.Collection)) { _ref1 = [new kb.Collection(), collection], collection = _ref1[0], options = _ref1[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 = {}); 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, KEYS_PUBLISH); _this._collection = ko.observable(collection); observable.collection = _this.collection = ko.computed({ 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._onCollectionChange); } if (new_collection) { new_collection.bind('all', _this._onCollectionChange); } return _this._collection(new_collection); }); } }); if (collection) { collection.bind('all', _this._onCollectionChange); } _this._mapper = ko.computed(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; this.__kb_released = true; observable = kb.utils.wrappedObservable(this); collection = kb.peek(this._collection); if (collection) { collection.unbind('all', this._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 _ref1; if (test != null ? (_ref1 = test.__kb) != null ? _ref1.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++; if ((comparator = _this._comparator())) { observable().push(_this._createViewModel(arg)); observable.sort(comparator); } else { observable.splice(collection.indexOf(arg), 0, _this._createViewModel(arg)); } _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, _ref1; 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 (_ref1 = model.id, __indexOf.call(filter, _ref1) < 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__) { var ALL_ORMS, kb, key, ko, value, _, _ref; _ref = kb = __webpack_require__(6), _ = _ref._, ko = _ref.ko; ALL_ORMS = { "default": null, 'backbone-orm': null, 'backbone-associations': __webpack_require__(16), 'backbone-relational': __webpack_require__(17), supermodel: __webpack_require__(18) }; kb.orm = ALL_ORMS["default"]; for (key in ALL_ORMS) { value = ALL_ORMS[key]; if (value && value.isAvailable()) { kb.orm = value; break; } } module.exports = function(options) { var orm; if (options == null) { options = {}; } for (key in options) { value = options[key]; switch (key) { case 'orm': if (_.isString(value)) { if (!ALL_ORMS.hasOwnProperty(value)) { console.log("Knockback configure: could not find orm: " + value + ". Available: " + (_.keys(ALL_ORMS).join(', '))); continue; } if ((orm = ALL_ORMS[value]) && !orm.isAvailable()) { console.log("Knockback configure: could not enable orm " + value + ". Make sure it is included before Knockback"); continue; } kb.orm = orm; continue; } else { kb.orm = value; } break; default: kb[key] = value; } } }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.19.4 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, _, _ref, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; _ref = kb = __webpack_require__(6), _ = _ref._, ko = _ref.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._unbindCallbacks = __bind(this._unbindCallbacks, this); this._onModelUnloaded = __bind(this._onModelUnloaded, this); this._onModelLoaded = __bind(this._onModelLoaded, this); this.__kb || (this.__kb = {}); this.__kb.callbacks = {}; this.ee = null; if (callback_options) { this.registerCallbacks(obj, callback_options); } if (emitter) { this.emitter(emitter); } } EventWatcher.prototype.destroy = function() { this.emitter(null); this.__kb.callbacks = null; return kb.utils.wrappedDestroy(this); }; EventWatcher.prototype.emitter = function(new_emitter) { if ((arguments.length === 0) || (this.ee === new_emitter)) { return this.ee; } if (this.model_ref) { this.model_ref.unbind('loaded', this._onModelLoaded); this.model_ref.unbind('unloaded', this._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._onModelLoaded); this.model_ref.bind('unloaded', this._onModelUnloaded); new_emitter = this.model_ref.model() || null; } else { delete this.model_ref; } if (this.ee !== new_emitter) { if (new_emitter) { this._onModelLoaded(new_emitter); } else { this._onModelUnloaded(this.ee); } } return new_emitter; }; EventWatcher.prototype.registerCallbacks = function(obj, callback_info) { var event_name, event_names, model, _fn, _i, _len; obj || kb._throwMissing(this, 'obj'); callback_info || kb._throwMissing(this, 'callback_info'); event_names = callback_info.event_selector ? callback_info.event_selector.split(' ') : ['change']; model = this.ee; _fn = (function(_this) { return function(event_name) { var callbacks, info; if (!(callbacks = _this.__kb.callbacks[event_name])) { callbacks = _this.__kb.callbacks[event_name] = { model: null, list: [], fn: function(model) { var info, _j, _len1, _ref1; _ref1 = callbacks.list; for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { info = _ref1[_j]; if (!info.update) { continue; } 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; } }; } callbacks.list.push(info = _.defaults({ obj: obj }, callback_info)); if (model) { return _this._onModelLoaded(model); } }; })(this); for (_i = 0, _len = event_names.length; _i < _len; _i++) { event_name = event_names[_i]; if (!event_name) { continue; } _fn(event_name); } return this; }; EventWatcher.prototype.releaseCallbacks = function(obj) { var callbacks, event_name, _ref1; this.ee = null; _ref1 = this.__kb.callbacks; for (event_name in _ref1) { callbacks = _ref1[event_name]; this._unbindCallbacks(event_name, callbacks, kb.wasReleased(obj)); } return delete this.__kb.callbacks; }; EventWatcher.prototype._onModelLoaded = function(model) { var callbacks, event_name, info, _i, _len, _ref1, _ref2, _ref3; this.ee = model; _ref1 = this.__kb.callbacks; for (event_name in _ref1) { callbacks = _ref1[event_name]; if (callbacks.model && (callbacks.model !== model)) { this._unbindCallbacks(event_name, callbacks, true); } if (!callbacks.model) { callbacks.model = model; model.bind(event_name, callbacks.fn); } _ref2 = callbacks.list; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { info = _ref2[_i]; info.unbind_fn || (info.unbind_fn = (_ref3 = kb.orm) != null ? _ref3.bind(model, info.key, info.update, info.path) : void 0); if (info.emitter) { info.emitter(model); } } } }; EventWatcher.prototype._onModelUnloaded = function(model) { var callbacks, event_name, _ref1; if (this.ee !== model) { return; } this.ee = null; _ref1 = this.__kb.callbacks; for (event_name in _ref1) { callbacks = _ref1[event_name]; this._unbindCallbacks(event_name, callbacks); } }; EventWatcher.prototype._unbindCallbacks = function(event_name, callbacks, skip_emitter) { var info, _i, _len, _ref1; if (callbacks.model) { callbacks.model.unbind(event_name, callbacks.fn); callbacks.model = null; } _ref1 = callbacks.list; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { info = _ref1[_i]; if (info.unbind_fn) { info.unbind_fn(); info.unbind_fn = null; } if (info.emitter && !skip_emitter && !kb.wasReleased(info.obj)) { info.emitter(null); } } }; return EventWatcher; })(); kb.emitterObservable = function(emitter, observable) { return new kb.EventWatcher(emitter, observable); }; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.19.4 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__(6))._; 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; })(); /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) { /* knockback.js 0.19.4 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, _ref; window = window != null ? window : global; _ref = kb = __webpack_require__(6), _ = _ref._, ko = _ref.ko, $ = _ref.$; 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; 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 { return kb.ignore(function() { return inject(data); }); } }; 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, _ref1; 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 }); } } _ref1 = el.childNodes; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { child_el = _ref1[_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; }()))) /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) { /* knockback.js 0.19.4 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__(21); 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.19.4'; 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') || kb.isModel(obj) || kb.isCollection(obj)) { 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))) { return obj.destroy(); } for (index in array) { value = array[index]; if (kb.isReleaseable(value)) { array[index] = null; kb.release(value); } } if (typeof obj.dispose === 'function') { obj.dispose(); } return; } 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.childNodes.length === 1) { el = el.childNodes[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) { var _ref; if (!model) { return; } if (_.isFunction(model[key]) && ((_ref = kb.orm) != null ? _ref.useFunction(model, key) : void 0)) { 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, _ref; if (!model) { return; } if (_.isFunction(model[key]) && ((_ref = kb.orm) != null ? _ref.useFunction(model, key) : void 0)) { 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.computed(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(); }); }; kb.isModel = function(obj) { return obj && ((obj instanceof kb.Model) || ((typeof obj.get === 'function') && (typeof obj.bind === 'function'))); }; kb.isCollection = function(obj) { return obj && (obj instanceof kb.Collection); }; return kb; })(); if (window.Parse) { Backbone = kb.Parse = window.Parse; _ = kb._ = window.Parse._; } else { Backbone = kb.Backbone = __webpack_require__(19); _ = kb._ = __webpack_require__(20); } 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__(15)); } catch (_error) {} /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.19.4 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, _extend, _ref, _ref1; ko = (kb = __webpack_require__(6)).ko; if ((_ref = ko.subscribable) != null ? (_ref1 = _ref.fn) != null ? _ref1.extend : void 0 : void 0) { _extend = ko.subscribable.fn.extend; ko.subscribable.fn.extend = function() { var target, _dispose; target = _extend.apply(this, arguments); if (target !== this && kb.isReleaseable(this)) { _dispose = target.dispose; target.dispose = (function(_this) { return function() { if (_dispose != null) { _dispose.apply(target, arguments); } return kb.release(_this); }; })(this); } return target; }; } /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.19.4 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 KEYS_INFO, KEYS_PUBLISH, TypedValue, kb, ko, _, _ref; _ref = kb = __webpack_require__(6), _ = _ref._, ko = _ref.ko; TypedValue = __webpack_require__(11); KEYS_PUBLISH = ['value', 'valueType', 'destroy']; KEYS_INFO = ['args', 'read', 'write']; kb.Observable = (function() { function Observable(model, key_or_info, options, _vm) { this._vm = _vm != null ? _vm : {}; return kb.ignore((function(_this) { return function() { var create_options, event_watcher, key, observable, _i, _len; key_or_info || kb._throwMissing(_this, 'key_or_info'); _this.key = key_or_info.key || key_or_info; for (_i = 0, _len = KEYS_INFO.length; _i < _len; _i++) { key = KEYS_INFO[_i]; if (key_or_info[key]) { _this[key] = key_or_info[key]; } } create_options = kb.utils.collapseOptions(options); event_watcher = create_options.event_watcher; delete create_options.event_watcher; _this._value = new TypedValue(create_options); _this._model = ko.observable(); observable = kb.utils.wrappedObservable(_this, ko.computed({ read: function() { var arg, args, _j, _len1, _model, _ref1, _ref2; _model = _this._model(); _ref1 = args = [_this.key].concat(_this.args || []); for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { arg = _ref1[_j]; ko.utils.unwrapObservable(arg); } if ((_ref2 = kb.utils.wrappedEventWatcher(_this)) != null) { _ref2.emitter(_model || null); } 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 _this._value.value(); }, 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, KEYS_PUBLISH); observable.model = _this.model = ko.computed({ 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 || null, _this, { emitter: _this.model, update: (function() { return kb.ignore(function() { return _this.update(); }); }), key: _this.key, path: create_options.path }); _this._value.rawValue() || _this._value.update(); if (kb.LocalizedObservable && key_or_info.localizer) { observable = new key_or_info.localizer(observable); } if (kb.DefaultObservable && key_or_info.hasOwnProperty('default')) { observable = kb.defaultObservable(observable, key_or_info["default"]); } return observable; }; })(this)); } Observable.prototype.destroy = function() { var observable; observable = kb.utils.wrappedObservable(this); this.__kb_released = true; this._value.destroy(); this._value = null; this.model.dispose(); this.model = observable.model = null; return kb.utils.wrappedDestroy(this); }; Observable.prototype.value = function() { return this._value.rawValue(); }; Observable.prototype.valueType = function() { return this._value.valueType(kb.peek(this._model), kb.peek(this.key)); }; Observable.prototype.update = function(new_value) { if (this.__kb_released) { return; } if (!arguments.length) { new_value = kb.getValue(kb.peek(this._model), kb.peek(this.key)); } return this._value.update(new_value); }; return Observable; })(); kb.observable = function(model, key, options, view_model) { return new kb.Observable(model, key, options, view_model); }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.19.4 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__(6))._; 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; }; Statistics.eventsStats = function(obj, key) { var events, node, stats, tail, _i, _len, _ref; stats = { count: 0 }; events = obj._events || obj._callbacks || {}; _ref = (key ? [key] : _.keys(events)); for (_i = 0, _len = _ref.length; _i < _len; _i++) { key = _ref[_i]; if (!(node = events[key])) { continue; } if (_.isArray(node)) { stats[key] = _.compact(node).length; } else { stats[key] = 0; tail = node.tail; while ((node = node.next) !== tail) { stats[key]++; } } stats.count += stats[key]; } return stats; }; return Statistics; })(); /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.19.4 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, _, _ref; _ref = kb = __webpack_require__(6), _ = _ref._, ko = _ref.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 observable_records, record, replaced_observables, _i, _len, _ref1, _ref2; _ref1 = [this.observable_records, []], observable_records = _ref1[0], this.observable_records = _ref1[1]; for (_i = 0, _len = observable_records.length; _i < _len; _i++) { record = observable_records[_i]; kb.release(record.observable); } _ref2 = [this.replaced_observables, []], replaced_observables = _ref2[0], this.replaced_observables = _ref2[1]; kb.release(replaced_observables); }; Store.prototype.compact = function() { var record, removals, _i, _len, _ref1, _ref2; removals = []; _ref1 = this.observable_records; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { record = _ref1[_i]; if ((_ref2 = record.observable) != null ? _ref2.__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, _ref1; removals = []; if (!obj || kb.isModel(obj)) { _ref1 = this.observable_records; for (index in _ref1) { record = _ref1[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, _ref1; _ref1 = this.observable_records; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { record = _ref1[_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 && kb.isModel(obj)) { 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; })(); /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var TypedValue, kb, ko, _, _ref; _ref = kb = __webpack_require__(6), _ = _ref._, ko = _ref.ko; module.exports = TypedValue = (function() { function TypedValue(create_options) { this.create_options = create_options; this._vo = ko.observable(null); } TypedValue.prototype.destroy = function() { this.__kb_released = true; kb.release(this.__kb_value); return this.__kb_value = null; }; TypedValue.prototype.value = function() { return ko.utils.unwrapObservable(this._vo()); }; TypedValue.prototype.rawValue = function() { return this.__kb_value; }; TypedValue.prototype.valueType = function(model, key) { var new_value; new_value = kb.getValue(model, key); this.value_type || this._updateValueObservable(new_value); return this.value_type; }; TypedValue.prototype.update = function(new_value) { var new_type, value; if (this.__kb_released) { return; } (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; switch (this.value_type) { case kb.TYPE_COLLECTION: if (this.value_type === kb.TYPE_COLLECTION && new_type === kb.TYPE_ARRAY) { return value(new_value); } if (new_type === kb.TYPE_COLLECTION || _.isNull(new_value)) { if (new_value && !kb.isCollection(new_value) && _.isFunction(new_value.collection)) { new_value = kb.peek(new_value.collection); } if (_.isFunction(value.collection)) { if (kb.peek(value.collection) !== new_value) { value.collection(new_value); } return; } } break; case kb.TYPE_MODEL: if (new_type === kb.TYPE_MODEL || _.isNull(new_value)) { if (new_value && !kb.isModel(new_value)) { new_value = _.isFunction(new_value.model) ? kb.peek(new_value.model) : kb.utils.wrappedObject(new_value); } if (_.isFunction(value.model)) { if (kb.peek(value.model) !== new_value) { value.model(new_value); } } else { if (kb.utils.wrappedObject(value) !== new_value) { this._updateValueObservable(new_value); } } return; } } if (this.value_type === new_type && !_.isUndefined(this.value_type)) { if (kb.peek(value) !== new_value) { return value(new_value); } } else { if (kb.peek(value) !== new_value) { return this._updateValueObservable(new_value); } } }; TypedValue.prototype._updateValueObservable = function(new_value) { var create_options, creator, previous_value, value; create_options = this.create_options; creator = create_options.creator = kb.utils.inferCreator(new_value, create_options.factory, create_options.path); this.value_type = kb.TYPE_UNKNOWN; 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 TypedValue; })(); /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.19.4 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, _ref, _wrappedKey; _ref = kb = __webpack_require__(6), _ = _ref._, ko = _ref.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) { var creator; if (factory && (creator = factory.creatorForPath(value, path))) { 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 (kb.isModel(obj)) { return kb.viewModel(obj, options); } if (kb.isCollection(obj)) { 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, _ref1; result = {}; options = { options: options }; while (options.options) { _ref1 = options.options; for (key in _ref1) { value = _ref1[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; })(); /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.19.4 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 KEYS_OPTIONS, assignViewModelKey, createObservable, createOptions, createStaticObservables, kb, ko, _, _ref; _ref = kb = __webpack_require__(6), _ = _ref._, ko = _ref.ko; createOptions = (function(_this) { return function(vm) { return { store: kb.utils.wrappedStore(vm), factory: kb.utils.wrappedFactory(vm), path: vm.__kb.path, event_watcher: kb.utils.wrappedEventWatcher(vm) }; }; })(this); assignViewModelKey = function(vm, key) { var vm_key; vm_key = vm.__kb.internals && _.contains(vm.__kb.internals, key) ? "_" + key : key; if (vm.__kb.view_model.hasOwnProperty(vm_key)) { return; } vm.__kb.view_model[vm_key] = null; return vm_key; }; createObservable = function(vm, model, key, create_options) { var vm_key; if (vm.__kb.excludes && _.contains(vm.__kb.excludes, key)) { return; } if (vm.__kb.statics && _.contains(vm.__kb.statics, key)) { return; } if (!(vm_key = assignViewModelKey(vm, key))) { return; } return vm[vm_key] = vm.__kb.view_model[vm_key] = kb.observable(model, key, create_options, vm); }; createStaticObservables = function(vm, model) { var key, vm_key, _i, _len, _ref1; _ref1 = vm.__kb.statics; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { key = _ref1[_i]; if (vm_key = assignViewModelKey(vm, key)) { if (model.has(vm_key)) { vm[vm_key] = vm.__kb.view_model[vm_key] = model.get(vm_key); } else if (vm.__kb.static_defaults && vm_key in vm.__kb.static_defaults) { vm[vm_key] = vm.__kb.view_model[vm_key] = vm.__kb.static_defaults[vm_key]; } else { delete vm.__kb.view_model[vm_key]; } } } }; KEYS_OPTIONS = ['keys', 'internals', 'excludes', 'statics', 'static_defaults']; kb.ViewModel = (function() { ViewModel.extend = kb.extend; function ViewModel(model, options, view_model) { if (options == null) { options = {}; } return kb.ignore((function(_this) { return function() { var create_options, event_watcher, key, _i, _len, _model; !model || (model instanceof kb.Model) || ((typeof model.get === 'function') && (typeof model.bind === 'function')) || kb._throwUnexpected(_this, 'not a model'); options = _.isArray(options) ? { keys: options } : kb.utils.collapseOptions(options); _this.__kb || (_this.__kb = {}); _this.__kb.view_model = view_model || _this; for (_i = 0, _len = KEYS_OPTIONS.length; _i < _len; _i++) { key = KEYS_OPTIONS[_i]; if (options.hasOwnProperty(key)) { _this.__kb[key] = options[key]; } } kb.Store.useOptionsOrCreate(options, model, _this); _this.__kb.path = options.path; kb.Factory.useOptionsOrCreate(options, _this, options.path); _model = kb._wrappedKey(_this, '_model', ko.observable()); _this.model = ko.computed({ read: function() { return ko.utils.unwrapObservable(_model); }, write: function(new_model) { return kb.ignore(function() { if ((kb.utils.wrappedObject(_this) === new_model) || kb.wasReleased(_this) || !event_watcher) { return; } if (_this.__kb_null) { !new_model || kb._throwUnexpected(_this, 'model set on shared null'); return; } event_watcher.emitter(new_model); kb.utils.wrappedObject(_this, event_watcher.ee); _model(event_watcher.ee); return !event_watcher.ee || _this.createObservables(event_watcher.ee); }); } }); event_watcher = kb.utils.wrappedEventWatcher(_this, new kb.EventWatcher(model, _this, { emitter: _this._model, update: (function() { return kb.ignore(function() { return !(event_watcher != null ? event_watcher.ee : void 0) || _this.createObservables(event_watcher != null ? event_watcher.ee : void 0); }); }) })); kb.utils.wrappedObject(_this, model = event_watcher.ee); _model(event_watcher.ee); create_options = createOptions(_this); !options.requires || _this.createObservables(model, options.requires, create_options); !_this.__kb.internals || _this.createObservables(model, _this.__kb.internals, create_options); !options.mappings || _this.createObservables(model, options.mappings, create_options); !_this.__kb.statics || createStaticObservables(_this, model); _this.createObservables(model, _this.__kb.keys, create_options); !kb.statistics || kb.statistics.register('ViewModel', _this); return _this; }; })(this)); } ViewModel.prototype.destroy = function() { var vm_key; this.__kb_released = true; 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, create_options) { var key, mapping_info, rel_keys, vm_key, _i, _j, _len, _len1, _ref1; create_options || (create_options = createOptions(this)); if (!keys) { if (this.__kb.keys || !model) { return; } for (key in model.attributes) { createObservable(this, model, key, create_options); } if (rel_keys = (_ref1 = kb.orm) != null ? typeof _ref1.keys === "function" ? _ref1.keys(model) : void 0 : void 0) { for (_i = 0, _len = rel_keys.length; _i < _len; _i++) { key = rel_keys[_i]; createObservable(this, model, key, create_options); } } } else if (_.isArray(keys)) { for (_j = 0, _len1 = keys.length; _j < _len1; _j++) { key = keys[_j]; createObservable(this, model, key, create_options); } } else { for (key in keys) { mapping_info = keys[key]; if (!(vm_key = assignViewModelKey(this, key))) { continue; } if (!_.isString(mapping_info)) { mapping_info.key || (mapping_info.key = vm_key); } this[vm_key] = this.__kb.view_model[vm_key] = kb.observable(model, mapping_info, create_options, this); } } }; return ViewModel; })(); kb.viewModel = function(model, options, view_model) { return new kb.ViewModel(model, options, view_model); }; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.19.4 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__(6); kb.configure = __webpack_require__(2); 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]; } } } /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { module.exports = __WEBPACK_EXTERNAL_MODULE_15__; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.19.4 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, Backbone, BackboneAssociations, kb, _, _ref; _ref = kb = __webpack_require__(6), _ = _ref._, Backbone = _ref.Backbone; AssociatedModel = null; module.exports = BackboneAssociations = (function() { function BackboneAssociations() {} BackboneAssociations.isAvailable = function() { return !!(AssociatedModel = Backbone != null ? Backbone.AssociatedModel : void 0); }; BackboneAssociations.keys = function(model) { if (!(model instanceof AssociatedModel)) { return null; } return _.map(model.relations, function(test) { return test.key; }); }; BackboneAssociations.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 BackboneAssociations; })(); /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /* knockback.js 0.19.4 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, BackboneRelational, RelationalModel, kb, _, _ref; _ref = kb = __webpack_require__(6), _ = _ref._, Backbone = _ref.Backbone; RelationalModel = null; module.exports = BackboneRelational = (function() { function BackboneRelational() {} BackboneRelational.isAvailable = function() { return !!(RelationalModel = Backbone != null ? Backbone.RelationalModel : void 0); }; BackboneRelational.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; } }; BackboneRelational.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 BackboneRelational; })(); /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) { /* knockback.js 0.19.4 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 Supermodel, kb, root, _; root = typeof window !== "undefined" && window !== null ? window : global; _ = (kb = __webpack_require__(6))._; Supermodel = null; module.exports = Supermodel = (function() { function Supermodel() {} Supermodel.isAvailable = function() { return !!(Supermodel = root.Supermodel); }; Supermodel.keys = function(model) { if (!(model instanceof Supermodel.Model)) { return null; } return _.keys(model.constructor.associations()); }; Supermodel.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; } }; Supermodel.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); }; } }; Supermodel.useFunction = function(model, key) { return !!this.relationType(model, key); }; return Supermodel; })(); /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 19 */ /***/ 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__(20), __webpack_require__(15), 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(exports, __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.$('