/*! * @overview Ember - JavaScript Application Framework * @copyright Copyright 2011-2015 Tilde Inc. and contributors * Portions Copyright 2006-2011 Strobe Inc. * Portions Copyright 2008-2011 Apple Inc. All rights reserved. * @license Licensed under MIT license * See https://raw.github.com/emberjs/ember.js/master/LICENSE * @version 1.13.0-beta.2 */ (function() { var enifed, requireModule, eriuqer, requirejs, Ember; var mainContext = this; (function() { Ember = this.Ember = this.Ember || {}; if (typeof Ember === 'undefined') { Ember = {}; }; if (typeof Ember.__loader === 'undefined') { var registry = {}; var seen = {}; enifed = function(name, deps, callback) { var value = { }; if (!callback) { value.deps = []; value.callback = deps; } else { value.deps = deps; value.callback = callback; } registry[name] = value; }; requirejs = eriuqer = requireModule = function(name) { return internalRequire(name, null); } function internalRequire(name, referrerName) { var exports = seen[name]; if (exports !== undefined) { return exports; } exports = seen[name] = {}; if (!registry[name]) { if (referrerName) { throw new Error('Could not find module ' + name + ' required by: ' + referrerName); } else { throw new Error('Could not find module ' + name); } } var mod = registry[name]; var deps = mod.deps; var callback = mod.callback; var reified = []; var length = deps.length; for (var i=0; i 3) { args = new Array(length - 3); for (var i = 3; i < length; i++) { args[i-3] = arguments[i]; } } else { args = undefined; } if (!this.currentInstance) { createAutorun(this); } return this.currentInstance.schedule(queueName, target, method, args, false, stack); }, deferOnce: function(queueName, target, method /* , args */) { if (!method) { method = target; target = null; } if (isString(method)) { method = target[method]; } var stack = this.DEBUG ? new Error() : undefined; var length = arguments.length; var args; if (length > 3) { args = new Array(length - 3); for (var i = 3; i < length; i++) { args[i-3] = arguments[i]; } } else { args = undefined; } if (!this.currentInstance) { createAutorun(this); } return this.currentInstance.schedule(queueName, target, method, args, true, stack); }, setTimeout: function() { var l = arguments.length; var args = new Array(l); for (var x = 0; x < l; x++) { args[x] = arguments[x]; } var length = args.length, method, wait, target, methodOrTarget, methodOrWait, methodOrArgs; if (length === 0) { return; } else if (length === 1) { method = args.shift(); wait = 0; } else if (length === 2) { methodOrTarget = args[0]; methodOrWait = args[1]; if (isFunction(methodOrWait) || isFunction(methodOrTarget[methodOrWait])) { target = args.shift(); method = args.shift(); wait = 0; } else if (isCoercableNumber(methodOrWait)) { method = args.shift(); wait = args.shift(); } else { method = args.shift(); wait = 0; } } else { var last = args[args.length - 1]; if (isCoercableNumber(last)) { wait = args.pop(); } else { wait = 0; } methodOrTarget = args[0]; methodOrArgs = args[1]; if (isFunction(methodOrArgs) || (isString(methodOrArgs) && methodOrTarget !== null && methodOrArgs in methodOrTarget)) { target = args.shift(); method = args.shift(); } else { method = args.shift(); } } var executeAt = now() + parseInt(wait, 10); if (isString(method)) { method = target[method]; } var onError = getOnError(this.options); function fn() { if (onError) { try { method.apply(target, args); } catch (e) { onError(e); } } else { method.apply(target, args); } } // find position to insert var i = searchTimer(executeAt, this._timers); this._timers.splice(i, 0, executeAt, fn); updateLaterTimer(this, executeAt, wait); return fn; }, throttle: function(target, method /* , args, wait, [immediate] */) { var backburner = this; var args = arguments; var immediate = pop.call(args); var wait, throttler, index, timer; if (isNumber(immediate) || isString(immediate)) { wait = immediate; immediate = true; } else { wait = pop.call(args); } wait = parseInt(wait, 10); index = findThrottler(target, method, this._throttlers); if (index > -1) { return this._throttlers[index]; } // throttled timer = global.setTimeout(function() { if (!immediate) { backburner.run.apply(backburner, args); } var index = findThrottler(target, method, backburner._throttlers); if (index > -1) { backburner._throttlers.splice(index, 1); } }, wait); if (immediate) { this.run.apply(this, args); } throttler = [target, method, timer]; this._throttlers.push(throttler); return throttler; }, debounce: function(target, method /* , args, wait, [immediate] */) { var backburner = this; var args = arguments; var immediate = pop.call(args); var wait, index, debouncee, timer; if (isNumber(immediate) || isString(immediate)) { wait = immediate; immediate = false; } else { wait = pop.call(args); } wait = parseInt(wait, 10); // Remove debouncee index = findDebouncee(target, method, this._debouncees); if (index > -1) { debouncee = this._debouncees[index]; this._debouncees.splice(index, 1); clearTimeout(debouncee[2]); } timer = global.setTimeout(function() { if (!immediate) { backburner.run.apply(backburner, args); } var index = findDebouncee(target, method, backburner._debouncees); if (index > -1) { backburner._debouncees.splice(index, 1); } }, wait); if (immediate && index === -1) { backburner.run.apply(backburner, args); } debouncee = [ target, method, timer ]; backburner._debouncees.push(debouncee); return debouncee; }, cancelTimers: function() { var clearItems = function(item) { clearTimeout(item[2]); }; each(this._throttlers, clearItems); this._throttlers = []; each(this._debouncees, clearItems); this._debouncees = []; if (this._laterTimer) { clearTimeout(this._laterTimer); this._laterTimer = null; } this._timers = []; if (this._autorun) { clearTimeout(this._autorun); this._autorun = null; } }, hasTimers: function() { return !!this._timers.length || !!this._debouncees.length || !!this._throttlers.length || this._autorun; }, cancel: function(timer) { var timerType = typeof timer; if (timer && timerType === 'object' && timer.queue && timer.method) { // we're cancelling a deferOnce return timer.queue.cancel(timer); } else if (timerType === 'function') { // we're cancelling a setTimeout for (var i = 0, l = this._timers.length; i < l; i += 2) { if (this._timers[i + 1] === timer) { this._timers.splice(i, 2); // remove the two elements if (i === 0) { if (this._laterTimer) { // Active timer? Then clear timer and reset for future timer clearTimeout(this._laterTimer); this._laterTimer = null; } if (this._timers.length > 0) { // Update to next available timer when available updateLaterTimer(this, this._timers[0], this._timers[0] - now()); } } return true; } } } else if (Object.prototype.toString.call(timer) === "[object Array]"){ // we're cancelling a throttle or debounce return this._cancelItem(findThrottler, this._throttlers, timer) || this._cancelItem(findDebouncee, this._debouncees, timer); } else { return; // timer was null or not a timer } }, _cancelItem: function(findMethod, array, timer){ var item, index; if (timer.length < 3) { return false; } index = findMethod(timer[0], timer[1], array); if (index > -1) { item = array[index]; if (item[2] === timer[2]) { array.splice(index, 1); clearTimeout(timer[2]); return true; } } return false; } }; Backburner.prototype.schedule = Backburner.prototype.defer; Backburner.prototype.scheduleOnce = Backburner.prototype.deferOnce; Backburner.prototype.later = Backburner.prototype.setTimeout; if (needsIETryCatchFix) { var originalRun = Backburner.prototype.run; Backburner.prototype.run = wrapInTryCatch(originalRun); var originalEnd = Backburner.prototype.end; Backburner.prototype.end = wrapInTryCatch(originalEnd); } function getOnError(options) { return options.onError || (options.onErrorTarget && options.onErrorTarget[options.onErrorMethod]); } function createAutorun(backburner) { backburner.begin(); backburner._autorun = global.setTimeout(function() { backburner._autorun = null; backburner.end(); }); } function updateLaterTimer(backburner, executeAt, wait) { var n = now(); if (!backburner._laterTimer || executeAt < backburner._laterTimerExpiresAt || backburner._laterTimerExpiresAt < n) { if (backburner._laterTimer) { // Clear when: // - Already expired // - New timer is earlier clearTimeout(backburner._laterTimer); if (backburner._laterTimerExpiresAt < n) { // If timer was never triggered // Calculate the left-over wait-time wait = Math.max(0, executeAt - n); } } backburner._laterTimer = global.setTimeout(function() { backburner._laterTimer = null; backburner._laterTimerExpiresAt = null; executeTimers(backburner); }, wait); backburner._laterTimerExpiresAt = n + wait; } } function executeTimers(backburner) { var n = now(); var fns, i, l; backburner.run(function() { i = searchTimer(n, backburner._timers); fns = backburner._timers.splice(0, i); for (i = 1, l = fns.length; i < l; i += 2) { backburner.schedule(backburner.options.defaultQueue, null, fns[i]); } }); if (backburner._timers.length) { updateLaterTimer(backburner, backburner._timers[0], backburner._timers[0] - n); } } function findDebouncee(target, method, debouncees) { return findItem(target, method, debouncees); } function findThrottler(target, method, throttlers) { return findItem(target, method, throttlers); } function findItem(target, method, collection) { var item; var index = -1; for (var i = 0, l = collection.length; i < l; i++) { item = collection[i]; if (item[0] === target && item[1] === method) { index = i; break; } } return index; } __exports__["default"] = Backburner; }); enifed("backburner.umd", ["./backburner"], function(__dependency1__) { "use strict"; var Backburner = __dependency1__["default"]; /* global define:true module:true window: true */ if (typeof enifed === 'function' && enifed.amd) { enifed(function() { return Backburner; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports = Backburner; } else if (typeof this !== 'undefined') { this['Backburner'] = Backburner; } }); enifed("backburner/binary-search", ["exports"], function(__exports__) { "use strict"; __exports__["default"] = function binarySearch(time, timers) { var start = 0; var end = timers.length - 2; var middle, l; while (start < end) { // since timers is an array of pairs 'l' will always // be an integer l = (end - start) / 2; // compensate for the index in case even number // of pairs inside timers middle = start + l - (l % 2); if (time >= timers[middle]) { start = middle + 2; } else { end = middle; } } return (time >= timers[start]) ? start + 2 : start; } }); enifed("backburner/deferred-action-queues", ["./utils","./queue","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var each = __dependency1__.each; var Queue = __dependency2__["default"]; function DeferredActionQueues(queueNames, options) { var queues = this.queues = Object.create(null); this.queueNames = queueNames = queueNames || []; this.options = options; each(queueNames, function(queueName) { queues[queueName] = new Queue(queueName, options[queueName], options); }); } function noSuchQueue(name) { throw new Error("You attempted to schedule an action in a queue (" + name + ") that doesn't exist"); } DeferredActionQueues.prototype = { schedule: function(name, target, method, args, onceFlag, stack) { var queues = this.queues; var queue = queues[name]; if (!queue) { noSuchQueue(name); } if (onceFlag) { return queue.pushUnique(target, method, args, stack); } else { return queue.push(target, method, args, stack); } }, flush: function() { var queues = this.queues; var queueNames = this.queueNames; var queueName, queue, queueItems, priorQueueNameIndex; var queueNameIndex = 0; var numberOfQueues = queueNames.length; var options = this.options; while (queueNameIndex < numberOfQueues) { queueName = queueNames[queueNameIndex]; queue = queues[queueName]; var numberOfQueueItems = queue._queue.length; if (numberOfQueueItems === 0) { queueNameIndex++; } else { queue.flush(false /* async */); queueNameIndex = 0; } } } }; __exports__["default"] = DeferredActionQueues; }); enifed("backburner/platform", ["exports"], function(__exports__) { "use strict"; // In IE 6-8, try/finally doesn't work without a catch. // Unfortunately, this is impossible to test for since wrapping it in a parent try/catch doesn't trigger the bug. // This tests for another broken try/catch behavior that only exhibits in the same versions of IE. var needsIETryCatchFix = (function(e,x){ try{ x(); } catch(e) { } // jshint ignore:line return !!e; })(); __exports__.needsIETryCatchFix = needsIETryCatchFix; }); enifed("backburner/queue", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; var isString = __dependency1__.isString; function Queue(name, options, globalOptions) { this.name = name; this.globalOptions = globalOptions || {}; this.options = options; this._queue = []; this.targetQueues = Object.create(null); this._queueBeingFlushed = undefined; } Queue.prototype = { push: function(target, method, args, stack) { var queue = this._queue; queue.push(target, method, args, stack); return { queue: this, target: target, method: method }; }, pushUniqueWithoutGuid: function(target, method, args, stack) { var queue = this._queue; for (var i = 0, l = queue.length; i < l; i += 4) { var currentTarget = queue[i]; var currentMethod = queue[i+1]; if (currentTarget === target && currentMethod === method) { queue[i+2] = args; // replace args queue[i+3] = stack; // replace stack return; } } queue.push(target, method, args, stack); }, targetQueue: function(targetQueue, target, method, args, stack) { var queue = this._queue; for (var i = 0, l = targetQueue.length; i < l; i += 4) { var currentMethod = targetQueue[i]; var currentIndex = targetQueue[i + 1]; if (currentMethod === method) { queue[currentIndex + 2] = args; // replace args queue[currentIndex + 3] = stack; // replace stack return; } } targetQueue.push( method, queue.push(target, method, args, stack) - 4 ); }, pushUniqueWithGuid: function(guid, target, method, args, stack) { var hasLocalQueue = this.targetQueues[guid]; if (hasLocalQueue) { this.targetQueue(hasLocalQueue, target, method, args, stack); } else { this.targetQueues[guid] = [ method, this._queue.push(target, method, args, stack) - 4 ]; } return { queue: this, target: target, method: method }; }, pushUnique: function(target, method, args, stack) { var queue = this._queue, currentTarget, currentMethod, i, l; var KEY = this.globalOptions.GUID_KEY; if (target && KEY) { var guid = target[KEY]; if (guid) { return this.pushUniqueWithGuid(guid, target, method, args, stack); } } this.pushUniqueWithoutGuid(target, method, args, stack); return { queue: this, target: target, method: method }; }, invoke: function(target, method, args, _, _errorRecordedForStack) { if (args && args.length > 0) { method.apply(target, args); } else { method.call(target); } }, invokeWithOnError: function(target, method, args, onError, errorRecordedForStack) { try { if (args && args.length > 0) { method.apply(target, args); } else { method.call(target); } } catch(error) { onError(error, errorRecordedForStack); } }, flush: function(sync) { var queue = this._queue; var length = queue.length; if (length === 0) { return; } var globalOptions = this.globalOptions; var options = this.options; var before = options && options.before; var after = options && options.after; var onError = globalOptions.onError || (globalOptions.onErrorTarget && globalOptions.onErrorTarget[globalOptions.onErrorMethod]); var target, method, args, errorRecordedForStack; var invoke = onError ? this.invokeWithOnError : this.invoke; this.targetQueues = Object.create(null); var queueItems = this._queueBeingFlushed = this._queue.slice(); this._queue = []; if (before) { before(); } for (var i = 0; i < length; i += 4) { target = queueItems[i]; method = queueItems[i+1]; args = queueItems[i+2]; errorRecordedForStack = queueItems[i+3]; // Debugging assistance if (isString(method)) { method = target[method]; } // method could have been nullified / canceled during flush if (method) { // // ** Attention intrepid developer ** // // To find out the stack of this task when it was scheduled onto // the run loop, add the following to your app.js: // // Ember.run.backburner.DEBUG = true; // NOTE: This slows your app, don't leave it on in production. // // Once that is in place, when you are at a breakpoint and navigate // here in the stack explorer, you can look at `errorRecordedForStack.stack`, // which will be the captured stack when this job was scheduled. // invoke(target, method, args, onError, errorRecordedForStack); } } if (after) { after(); } this._queueBeingFlushed = undefined; if (sync !== false && this._queue.length > 0) { // check if new items have been added this.flush(true); } }, cancel: function(actionToCancel) { var queue = this._queue, currentTarget, currentMethod, i, l; var target = actionToCancel.target; var method = actionToCancel.method; var GUID_KEY = this.globalOptions.GUID_KEY; if (GUID_KEY && this.targetQueues && target) { var targetQueue = this.targetQueues[target[GUID_KEY]]; if (targetQueue) { for (i = 0, l = targetQueue.length; i < l; i++) { if (targetQueue[i] === method) { targetQueue.splice(i, 1); } } } } for (i = 0, l = queue.length; i < l; i += 4) { currentTarget = queue[i]; currentMethod = queue[i+1]; if (currentTarget === target && currentMethod === method) { queue.splice(i, 4); return true; } } // if not found in current queue // could be in the queue that is being flushed queue = this._queueBeingFlushed; if (!queue) { return; } for (i = 0, l = queue.length; i < l; i += 4) { currentTarget = queue[i]; currentMethod = queue[i+1]; if (currentTarget === target && currentMethod === method) { // don't mess with array during flush // just nullify the method queue[i+1] = null; return true; } } } }; __exports__["default"] = Queue; }); enifed("backburner/utils", ["exports"], function(__exports__) { "use strict"; var NUMBER = /\d+/; function each(collection, callback) { for (var i = 0; i < collection.length; i++) { callback(collection[i]); } } __exports__.each = each;// Date.now is not available in browsers < IE9 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility var now = Date.now || function() { return new Date().getTime(); }; __exports__.now = now; function isString(suspect) { return typeof suspect === 'string'; } __exports__.isString = isString;function isFunction(suspect) { return typeof suspect === 'function'; } __exports__.isFunction = isFunction;function isNumber(suspect) { return typeof suspect === 'number'; } __exports__.isNumber = isNumber;function isCoercableNumber(number) { return isNumber(number) || NUMBER.test(number); } __exports__.isCoercableNumber = isCoercableNumber;function wrapInTryCatch(func) { return function () { try { return func.apply(this, arguments); } catch (e) { throw e; } }; } __exports__.wrapInTryCatch = wrapInTryCatch; }); enifed("calculateVersion", [], function() { "use strict"; 'use strict'; var fs = eriuqer('fs'); var path = eriuqer('path'); module.exports = function () { var packageVersion = eriuqer('../package.json').version; var output = [packageVersion]; var gitPath = path.join(__dirname,'..','.git'); var headFilePath = path.join(gitPath, 'HEAD'); if (packageVersion.indexOf('+') > -1) { try { if (fs.existsSync(headFilePath)) { var headFile = fs.readFileSync(headFilePath, {encoding: 'utf8'}); var branchName = headFile.split('/').slice(-1)[0].trim(); var refPath = headFile.split(' ')[1]; var branchSHA; if (refPath) { var branchPath = path.join(gitPath, refPath.trim()); branchSHA = fs.readFileSync(branchPath); } else { branchSHA = branchName; } output.push(branchSHA.slice(0,10)); } } catch (err) { console.error(err.stack); } return output.join('.'); } else { return packageVersion; } }; }); enifed('container', ['exports', 'container/registry', 'container/container'], function (exports, Registry, Container) { 'use strict'; Ember.MODEL_FACTORY_INJECTIONS = false; if (Ember.ENV && typeof Ember.ENV.MODEL_FACTORY_INJECTIONS !== 'undefined') { Ember.MODEL_FACTORY_INJECTIONS = !!Ember.ENV.MODEL_FACTORY_INJECTIONS; } exports.Registry = Registry['default']; exports.Container = Container['default']; }); enifed('container/container', ['exports', 'ember-metal/core', 'ember-metal/keys', 'ember-metal/dictionary'], function (exports, Ember, emberKeys, dictionary) { 'use strict'; var Registry; /** A container used to instantiate and cache objects. Every `Container` must be associated with a `Registry`, which is referenced to determine the factory and options that should be used to instantiate objects. The public API for `Container` is still in flux and should not be considered stable. @private @class Container */ function Container(registry, options) { this._registry = registry || (function () { Ember['default'].deprecate('A container should only be created for an already instantiated registry. For backward compatibility, an isolated registry will be instantiated just for this container.'); // TODO - See note above about transpiler import workaround. if (!Registry) { Registry = requireModule('container/registry')['default']; } return new Registry(); })(); this.cache = dictionary['default'](options && options.cache ? options.cache : null); this.factoryCache = dictionary['default'](options && options.factoryCache ? options.factoryCache : null); this.validationCache = dictionary['default'](options && options.validationCache ? options.validationCache : null); } Container.prototype = { /** @private @property _registry @type Registry @since 1.11.0 */ _registry: null, /** @property cache @type InheritingDict */ cache: null, /** @property factoryCache @type InheritingDict */ factoryCache: null, /** @property validationCache @type InheritingDict */ validationCache: null, /** Given a fullName return a corresponding instance. The default behaviour is for lookup to return a singleton instance. The singleton is scoped to the container, allowing multiple containers to all have their own locally scoped singletons. ```javascript var registry = new Registry(); var container = registry.container(); registry.register('api:twitter', Twitter); var twitter = container.lookup('api:twitter'); twitter instanceof Twitter; // => true // by default the container will return singletons var twitter2 = container.lookup('api:twitter'); twitter2 instanceof Twitter; // => true twitter === twitter2; //=> true ``` If singletons are not wanted an optional flag can be provided at lookup. ```javascript var registry = new Registry(); var container = registry.container(); registry.register('api:twitter', Twitter); var twitter = container.lookup('api:twitter', { singleton: false }); var twitter2 = container.lookup('api:twitter', { singleton: false }); twitter === twitter2; //=> false ``` @method lookup @param {String} fullName @param {Object} options @return {any} */ lookup: function (fullName, options) { Ember['default'].assert('fullName must be a proper full name', this._registry.validateFullName(fullName)); return lookup(this, this._registry.normalize(fullName), options); }, /** Given a fullName return the corresponding factory. @method lookupFactory @param {String} fullName @return {any} */ lookupFactory: function (fullName) { Ember['default'].assert('fullName must be a proper full name', this._registry.validateFullName(fullName)); return factoryFor(this, this._registry.normalize(fullName)); }, /** A depth first traversal, destroying the container, its descendant containers and all their managed objects. @method destroy */ destroy: function () { eachDestroyable(this, function (item) { if (item.destroy) { item.destroy(); } }); this.isDestroyed = true; }, /** Clear either the entire cache or just the cache for a particular key. @method reset @param {String} fullName optional key to reset; if missing, resets everything */ reset: function (fullName) { if (arguments.length > 0) { resetMember(this, this._registry.normalize(fullName)); } else { resetCache(this); } } }; (function exposeRegistryMethods() { var methods = ['register', 'unregister', 'resolve', 'normalize', 'typeInjection', 'injection', 'factoryInjection', 'factoryTypeInjection', 'has', 'options', 'optionsForType']; function exposeRegistryMethod(method) { Container.prototype[method] = function () { Ember['default'].deprecate(method + ' should be called on the registry instead of the container'); return this._registry[method].apply(this._registry, arguments); }; } for (var i = 0, l = methods.length; i < l; i++) { exposeRegistryMethod(methods[i]); } })(); function lookup(container, fullName, options) { options = options || {}; if (container.cache[fullName] && options.singleton !== false) { return container.cache[fullName]; } var value = instantiate(container, fullName); if (value === undefined) { return; } if (container._registry.getOption(fullName, 'singleton') !== false && options.singleton !== false) { container.cache[fullName] = value; } return value; } function buildInjections(container) { var hash = {}; if (arguments.length > 1) { var injectionArgs = Array.prototype.slice.call(arguments, 1); var injections = []; var injection; for (var i = 0, l = injectionArgs.length; i < l; i++) { if (injectionArgs[i]) { injections = injections.concat(injectionArgs[i]); } } container._registry.validateInjections(injections); for (i = 0, l = injections.length; i < l; i++) { injection = injections[i]; hash[injection.property] = lookup(container, injection.fullName); } } return hash; } function factoryFor(container, fullName) { var cache = container.factoryCache; if (cache[fullName]) { return cache[fullName]; } var registry = container._registry; var factory = registry.resolve(fullName); if (factory === undefined) { return; } var type = fullName.split(':')[0]; if (!factory || typeof factory.extend !== 'function' || !Ember['default'].MODEL_FACTORY_INJECTIONS && type === 'model') { if (factory && typeof factory._onLookup === 'function') { factory._onLookup(fullName); } // TODO: think about a 'safe' merge style extension // for now just fallback to create time injection cache[fullName] = factory; return factory; } else { var injections = injectionsFor(container, fullName); var factoryInjections = factoryInjectionsFor(container, fullName); factoryInjections._toString = registry.makeToString(factory, fullName); var injectedFactory = factory.extend(injections); injectedFactory.reopenClass(factoryInjections); if (factory && typeof factory._onLookup === 'function') { factory._onLookup(fullName); } cache[fullName] = injectedFactory; return injectedFactory; } } function injectionsFor(container, fullName) { var registry = container._registry; var splitName = fullName.split(':'); var type = splitName[0]; var injections = buildInjections(container, registry.getTypeInjections(type), registry.getInjections(fullName)); injections._debugContainerKey = fullName; injections.container = container; return injections; } function factoryInjectionsFor(container, fullName) { var registry = container._registry; var splitName = fullName.split(':'); var type = splitName[0]; var factoryInjections = buildInjections(container, registry.getFactoryTypeInjections(type), registry.getFactoryInjections(fullName)); factoryInjections._debugContainerKey = fullName; return factoryInjections; } function instantiate(container, fullName) { var factory = factoryFor(container, fullName); var lazyInjections, validationCache; if (container._registry.getOption(fullName, 'instantiate') === false) { return factory; } if (factory) { if (typeof factory.create !== 'function') { throw new Error('Failed to create an instance of \'' + fullName + '\'. ' + 'Most likely an improperly defined class or an invalid module export.'); } validationCache = container.validationCache; // Ensure that all lazy injections are valid at instantiation time if (!validationCache[fullName] && typeof factory._lazyInjections === 'function') { lazyInjections = factory._lazyInjections(); lazyInjections = container._registry.normalizeInjectionsHash(lazyInjections); container._registry.validateInjections(lazyInjections); } validationCache[fullName] = true; if (typeof factory.extend === 'function') { // assume the factory was extendable and is already injected return factory.create(); } else { // assume the factory was extendable // to create time injections // TODO: support new'ing for instantiation and merge injections for pure JS Functions return factory.create(injectionsFor(container, fullName)); } } } function eachDestroyable(container, callback) { var cache = container.cache; var keys = emberKeys['default'](cache); var key, value; for (var i = 0, l = keys.length; i < l; i++) { key = keys[i]; value = cache[key]; if (container._registry.getOption(key, 'instantiate') !== false) { callback(value); } } } function resetCache(container) { eachDestroyable(container, function (value) { if (value.destroy) { value.destroy(); } }); container.cache.dict = dictionary['default'](null); } function resetMember(container, fullName) { var member = container.cache[fullName]; delete container.factoryCache[fullName]; if (member) { delete container.cache[fullName]; if (member.destroy) { member.destroy(); } } } exports['default'] = Container; }); enifed('container/registry', ['exports', 'ember-metal/core', 'ember-metal/dictionary', './container'], function (exports, Ember, dictionary, Container) { 'use strict'; var VALID_FULL_NAME_REGEXP = /^[^:]+.+:[^:]+$/; var instanceInitializersFeatureEnabled; instanceInitializersFeatureEnabled = true; /** A registry used to store factory and option information keyed by type. A `Registry` stores the factory and option information needed by a `Container` to instantiate and cache objects. The public API for `Registry` is still in flux and should not be considered stable. @private @class Registry @since 1.11.0 */ function Registry(options) { this.fallback = options && options.fallback ? options.fallback : null; this.resolver = options && options.resolver ? options.resolver : function () {}; this.registrations = dictionary['default'](options && options.registrations ? options.registrations : null); this._typeInjections = dictionary['default'](null); this._injections = dictionary['default'](null); this._factoryTypeInjections = dictionary['default'](null); this._factoryInjections = dictionary['default'](null); this._normalizeCache = dictionary['default'](null); this._resolveCache = dictionary['default'](null); this._failCache = dictionary['default'](null); this._options = dictionary['default'](null); this._typeOptions = dictionary['default'](null); } Registry.prototype = { /** A backup registry for resolving registrations when no matches can be found. @property fallback @type Registry */ fallback: null, /** @property resolver @type function */ resolver: null, /** @property registrations @type InheritingDict */ registrations: null, /** @private @property _typeInjections @type InheritingDict */ _typeInjections: null, /** @private @property _injections @type InheritingDict */ _injections: null, /** @private @property _factoryTypeInjections @type InheritingDict */ _factoryTypeInjections: null, /** @private @property _factoryInjections @type InheritingDict */ _factoryInjections: null, /** @private @property _normalizeCache @type InheritingDict */ _normalizeCache: null, /** @private @property _resolveCache @type InheritingDict */ _resolveCache: null, /** @private @property _options @type InheritingDict */ _options: null, /** @private @property _typeOptions @type InheritingDict */ _typeOptions: null, /** The first container created for this registry. This allows deprecated access to `lookup` and `lookupFactory` to avoid breaking compatibility for Ember 1.x initializers. @private @property _defaultContainer @type Container */ _defaultContainer: null, /** Creates a container based on this registry. @method container @param {Object} options @return {Container} created container */ container: function (options) { var container = new Container['default'](this, options); // 2.0TODO - remove `registerContainer` this.registerContainer(container); return container; }, /** Register the first container created for a registery to allow deprecated access to its `lookup` and `lookupFactory` methods to avoid breaking compatibility for Ember 1.x initializers. 2.0TODO: Remove this method. The bookkeeping is only needed to support deprecated behavior. @param {Container} newly created container */ registerContainer: function (container) { if (!this._defaultContainer) { this._defaultContainer = container; } if (this.fallback) { this.fallback.registerContainer(container); } }, lookup: function (fullName, options) { Ember['default'].assert('Create a container on the registry (with `registry.container()`) before calling `lookup`.', this._defaultContainer); if (instanceInitializersFeatureEnabled) { Ember['default'].deprecate('`lookup` was called on a Registry. The `initializer` API no longer receives a container, and you should use an `instanceInitializer` to look up objects from the container.', false, { url: 'http://emberjs.com/guides/deprecations#toc_deprecate-access-to-instances-in-initializers' }); } return this._defaultContainer.lookup(fullName, options); }, lookupFactory: function (fullName) { Ember['default'].assert('Create a container on the registry (with `registry.container()`) before calling `lookupFactory`.', this._defaultContainer); if (instanceInitializersFeatureEnabled) { Ember['default'].deprecate('`lookupFactory` was called on a Registry. The `initializer` API no longer receives a container, and you should use an `instanceInitializer` to look up objects from the container.', false, { url: 'http://emberjs.com/guides/deprecations#toc_deprecate-access-to-instances-in-initializers' }); } return this._defaultContainer.lookupFactory(fullName); }, /** Registers a factory for later injection. Example: ```javascript var registry = new Registry(); registry.register('model:user', Person, {singleton: false }); registry.register('fruit:favorite', Orange); registry.register('communication:main', Email, {singleton: false}); ``` @method register @param {String} fullName @param {Function} factory @param {Object} options */ register: function (fullName, factory, options) { Ember['default'].assert('fullName must be a proper full name', this.validateFullName(fullName)); if (factory === undefined) { throw new TypeError('Attempting to register an unknown factory: `' + fullName + '`'); } var normalizedName = this.normalize(fullName); if (this._resolveCache[normalizedName]) { throw new Error('Cannot re-register: `' + fullName + '`, as it has already been resolved.'); } delete this._failCache[normalizedName]; this.registrations[normalizedName] = factory; this._options[normalizedName] = options || {}; }, /** Unregister a fullName ```javascript var registry = new Registry(); registry.register('model:user', User); registry.resolve('model:user').create() instanceof User //=> true registry.unregister('model:user') registry.resolve('model:user') === undefined //=> true ``` @method unregister @param {String} fullName */ unregister: function (fullName) { Ember['default'].assert('fullName must be a proper full name', this.validateFullName(fullName)); var normalizedName = this.normalize(fullName); delete this.registrations[normalizedName]; delete this._resolveCache[normalizedName]; delete this._failCache[normalizedName]; delete this._options[normalizedName]; }, /** Given a fullName return the corresponding factory. By default `resolve` will retrieve the factory from the registry. ```javascript var registry = new Registry(); registry.register('api:twitter', Twitter); registry.resolve('api:twitter') // => Twitter ``` Optionally the registry can be provided with a custom resolver. If provided, `resolve` will first provide the custom resolver the opportunity to resolve the fullName, otherwise it will fallback to the registry. ```javascript var registry = new Registry(); registry.resolver = function(fullName) { // lookup via the module system of choice }; // the twitter factory is added to the module system registry.resolve('api:twitter') // => Twitter ``` @method resolve @param {String} fullName @return {Function} fullName's factory */ resolve: function (fullName) { Ember['default'].assert('fullName must be a proper full name', this.validateFullName(fullName)); var factory = resolve(this, this.normalize(fullName)); if (factory === undefined && this.fallback) { factory = this.fallback.resolve(fullName); } return factory; }, /** A hook that can be used to describe how the resolver will attempt to find the factory. For example, the default Ember `.describe` returns the full class name (including namespace) where Ember's resolver expects to find the `fullName`. @method describe @param {String} fullName @return {string} described fullName */ describe: function (fullName) { return fullName; }, /** A hook to enable custom fullName normalization behaviour @method normalizeFullName @param {String} fullName @return {string} normalized fullName */ normalizeFullName: function (fullName) { return fullName; }, /** normalize a fullName based on the applications conventions @method normalize @param {String} fullName @return {string} normalized fullName */ normalize: function (fullName) { return this._normalizeCache[fullName] || (this._normalizeCache[fullName] = this.normalizeFullName(fullName)); }, /** @method makeToString @param {any} factory @param {string} fullName @return {function} toString function */ makeToString: function (factory, fullName) { return factory.toString(); }, /** Given a fullName check if the container is aware of its factory or singleton instance. @method has @param {String} fullName @return {Boolean} */ has: function (fullName) { Ember['default'].assert('fullName must be a proper full name', this.validateFullName(fullName)); return has(this, this.normalize(fullName)); }, /** Allow registering options for all factories of a type. ```javascript var registry = new Registry(); var container = registry.container(); // if all of type `connection` must not be singletons registry.optionsForType('connection', { singleton: false }); registry.register('connection:twitter', TwitterConnection); registry.register('connection:facebook', FacebookConnection); var twitter = container.lookup('connection:twitter'); var twitter2 = container.lookup('connection:twitter'); twitter === twitter2; // => false var facebook = container.lookup('connection:facebook'); var facebook2 = container.lookup('connection:facebook'); facebook === facebook2; // => false ``` @method optionsForType @param {String} type @param {Object} options */ optionsForType: function (type, options) { this._typeOptions[type] = options; }, getOptionsForType: function (type) { var optionsForType = this._typeOptions[type]; if (optionsForType === undefined && this.fallback) { optionsForType = this.fallback.getOptionsForType(type); } return optionsForType; }, /** @method options @param {String} fullName @param {Object} options */ options: function (fullName, options) { options = options || {}; var normalizedName = this.normalize(fullName); this._options[normalizedName] = options; }, getOptions: function (fullName) { var normalizedName = this.normalize(fullName); var options = this._options[normalizedName]; if (options === undefined && this.fallback) { options = this.fallback.getOptions(fullName); } return options; }, getOption: function (fullName, optionName) { var options = this._options[fullName]; if (options && options[optionName] !== undefined) { return options[optionName]; } var type = fullName.split(':')[0]; options = this._typeOptions[type]; if (options && options[optionName] !== undefined) { return options[optionName]; } else if (this.fallback) { return this.fallback.getOption(fullName, optionName); } }, option: function (fullName, optionName) { Ember['default'].deprecate('`Registry.option()` has been deprecated. Call `Registry.getOption()` instead.'); return this.getOption(fullName, optionName); }, /** Used only via `injection`. Provides a specialized form of injection, specifically enabling all objects of one type to be injected with a reference to another object. For example, provided each object of type `controller` needed a `router`. one would do the following: ```javascript var registry = new Registry(); var container = registry.container(); registry.register('router:main', Router); registry.register('controller:user', UserController); registry.register('controller:post', PostController); registry.typeInjection('controller', 'router', 'router:main'); var user = container.lookup('controller:user'); var post = container.lookup('controller:post'); user.router instanceof Router; //=> true post.router instanceof Router; //=> true // both controllers share the same router user.router === post.router; //=> true ``` @private @method typeInjection @param {String} type @param {String} property @param {String} fullName */ typeInjection: function (type, property, fullName) { Ember['default'].assert('fullName must be a proper full name', this.validateFullName(fullName)); var fullNameType = fullName.split(':')[0]; if (fullNameType === type) { throw new Error('Cannot inject a `' + fullName + '` on other ' + type + '(s).'); } var injections = this._typeInjections[type] || (this._typeInjections[type] = []); injections.push({ property: property, fullName: fullName }); }, /** Defines injection rules. These rules are used to inject dependencies onto objects when they are instantiated. Two forms of injections are possible: * Injecting one fullName on another fullName * Injecting one fullName on a type Example: ```javascript var registry = new Registry(); var container = registry.container(); registry.register('source:main', Source); registry.register('model:user', User); registry.register('model:post', Post); // injecting one fullName on another fullName // eg. each user model gets a post model registry.injection('model:user', 'post', 'model:post'); // injecting one fullName on another type registry.injection('model', 'source', 'source:main'); var user = container.lookup('model:user'); var post = container.lookup('model:post'); user.source instanceof Source; //=> true post.source instanceof Source; //=> true user.post instanceof Post; //=> true // and both models share the same source user.source === post.source; //=> true ``` @method injection @param {String} factoryName @param {String} property @param {String} injectionName */ injection: function (fullName, property, injectionName) { this.validateFullName(injectionName); var normalizedInjectionName = this.normalize(injectionName); if (fullName.indexOf(':') === -1) { return this.typeInjection(fullName, property, normalizedInjectionName); } Ember['default'].assert('fullName must be a proper full name', this.validateFullName(fullName)); var normalizedName = this.normalize(fullName); var injections = this._injections[normalizedName] || (this._injections[normalizedName] = []); injections.push({ property: property, fullName: normalizedInjectionName }); }, /** Used only via `factoryInjection`. Provides a specialized form of injection, specifically enabling all factory of one type to be injected with a reference to another object. For example, provided each factory of type `model` needed a `store`. one would do the following: ```javascript var registry = new Registry(); registry.register('store:main', SomeStore); registry.factoryTypeInjection('model', 'store', 'store:main'); var store = registry.lookup('store:main'); var UserFactory = registry.lookupFactory('model:user'); UserFactory.store instanceof SomeStore; //=> true ``` @private @method factoryTypeInjection @param {String} type @param {String} property @param {String} fullName */ factoryTypeInjection: function (type, property, fullName) { var injections = this._factoryTypeInjections[type] || (this._factoryTypeInjections[type] = []); injections.push({ property: property, fullName: this.normalize(fullName) }); }, /** Defines factory injection rules. Similar to regular injection rules, but are run against factories, via `Registry#lookupFactory`. These rules are used to inject objects onto factories when they are looked up. Two forms of injections are possible: * Injecting one fullName on another fullName * Injecting one fullName on a type Example: ```javascript var registry = new Registry(); var container = registry.container(); registry.register('store:main', Store); registry.register('store:secondary', OtherStore); registry.register('model:user', User); registry.register('model:post', Post); // injecting one fullName on another type registry.factoryInjection('model', 'store', 'store:main'); // injecting one fullName on another fullName registry.factoryInjection('model:post', 'secondaryStore', 'store:secondary'); var UserFactory = container.lookupFactory('model:user'); var PostFactory = container.lookupFactory('model:post'); var store = container.lookup('store:main'); UserFactory.store instanceof Store; //=> true UserFactory.secondaryStore instanceof OtherStore; //=> false PostFactory.store instanceof Store; //=> true PostFactory.secondaryStore instanceof OtherStore; //=> true // and both models share the same source instance UserFactory.store === PostFactory.store; //=> true ``` @method factoryInjection @param {String} factoryName @param {String} property @param {String} injectionName */ factoryInjection: function (fullName, property, injectionName) { var normalizedName = this.normalize(fullName); var normalizedInjectionName = this.normalize(injectionName); this.validateFullName(injectionName); if (fullName.indexOf(':') === -1) { return this.factoryTypeInjection(normalizedName, property, normalizedInjectionName); } var injections = this._factoryInjections[normalizedName] || (this._factoryInjections[normalizedName] = []); injections.push({ property: property, fullName: normalizedInjectionName }); }, validateFullName: function (fullName) { if (!VALID_FULL_NAME_REGEXP.test(fullName)) { throw new TypeError('Invalid Fullname, expected: `type:name` got: ' + fullName); } return true; }, validateInjections: function (injections) { if (!injections) { return; } var fullName; for (var i = 0, length = injections.length; i < length; i++) { fullName = injections[i].fullName; if (!this.has(fullName)) { throw new Error('Attempting to inject an unknown injection: `' + fullName + '`'); } } }, normalizeInjectionsHash: function (hash) { var injections = []; for (var key in hash) { if (hash.hasOwnProperty(key)) { Ember['default'].assert('Expected a proper full name, given \'' + hash[key] + '\'', this.validateFullName(hash[key])); injections.push({ property: key, fullName: hash[key] }); } } return injections; }, getInjections: function (fullName) { var injections = this._injections[fullName] || []; if (this.fallback) { injections = injections.concat(this.fallback.getInjections(fullName)); } return injections; }, getTypeInjections: function (type) { var injections = this._typeInjections[type] || []; if (this.fallback) { injections = injections.concat(this.fallback.getTypeInjections(type)); } return injections; }, getFactoryInjections: function (fullName) { var injections = this._factoryInjections[fullName] || []; if (this.fallback) { injections = injections.concat(this.fallback.getFactoryInjections(fullName)); } return injections; }, getFactoryTypeInjections: function (type) { var injections = this._factoryTypeInjections[type] || []; if (this.fallback) { injections = injections.concat(this.fallback.getFactoryTypeInjections(type)); } return injections; } }; function resolve(registry, normalizedName) { var cached = registry._resolveCache[normalizedName]; if (cached) { return cached; } if (registry._failCache[normalizedName]) { return; } var resolved = registry.resolver(normalizedName) || registry.registrations[normalizedName]; if (resolved) { registry._resolveCache[normalizedName] = resolved; } else { registry._failCache[normalizedName] = true; } return resolved; } function has(registry, fullName) { return registry.resolve(fullName) !== undefined; } exports['default'] = Registry; }); enifed("dag-map", ["exports"], function(__exports__) { "use strict"; function visit(vertex, fn, visited, path) { var name = vertex.name; var vertices = vertex.incoming; var names = vertex.incomingNames; var len = names.length; var i; if (!visited) { visited = {}; } if (!path) { path = []; } if (visited.hasOwnProperty(name)) { return; } path.push(name); visited[name] = true; for (i = 0; i < len; i++) { visit(vertices[names[i]], fn, visited, path); } fn(vertex, path); path.pop(); } /** * DAG stands for Directed acyclic graph. * * It is used to build a graph of dependencies checking that there isn't circular * dependencies. p.e Registering initializers with a certain precedence order. * * @class DAG * @constructor */ function DAG() { this.names = []; this.vertices = Object.create(null); } /** * DAG Vertex * * @class Vertex * @constructor */ function Vertex(name) { this.name = name; this.incoming = {}; this.incomingNames = []; this.hasOutgoing = false; this.value = null; } /** * Adds a vertex entry to the graph unless it is already added. * * @private * @method add * @param {String} name The name of the vertex to add */ DAG.prototype.add = function(name) { if (!name) { throw new Error("Can't add Vertex without name"); } if (this.vertices[name] !== undefined) { return this.vertices[name]; } var vertex = new Vertex(name); this.vertices[name] = vertex; this.names.push(name); return vertex; }; /** * Adds a vertex to the graph and sets its value. * * @private * @method map * @param {String} name The name of the vertex. * @param value The value to put in the vertex. */ DAG.prototype.map = function(name, value) { this.add(name).value = value; }; /** * Connects the vertices with the given names, adding them to the graph if * necessary, only if this does not produce is any circular dependency. * * @private * @method addEdge * @param {String} fromName The name the vertex where the edge starts. * @param {String} toName The name the vertex where the edge ends. */ DAG.prototype.addEdge = function(fromName, toName) { if (!fromName || !toName || fromName === toName) { return; } var from = this.add(fromName); var to = this.add(toName); if (to.incoming.hasOwnProperty(fromName)) { return; } function checkCycle(vertex, path) { if (vertex.name === toName) { throw new Error("cycle detected: " + toName + " <- " + path.join(" <- ")); } } visit(from, checkCycle); from.hasOutgoing = true; to.incoming[fromName] = from; to.incomingNames.push(fromName); }; /** * Visits all the vertex of the graph calling the given function with each one, * ensuring that the vertices are visited respecting their precedence. * * @method topsort * @param {Function} fn The function to be invoked on each vertex. */ DAG.prototype.topsort = function(fn) { var visited = {}; var vertices = this.vertices; var names = this.names; var len = names.length; var i, vertex; for (i = 0; i < len; i++) { vertex = vertices[names[i]]; if (!vertex.hasOutgoing) { visit(vertex, fn, visited); } } }; /** * Adds a vertex with the given name and value to the graph and joins it with the * vertices referenced in _before_ and _after_. If there isn't vertices with those * names, they are added too. * * If either _before_ or _after_ are falsy/empty, the added vertex will not have * an incoming/outgoing edge. * * @method addEdges * @param {String} name The name of the vertex to be added. * @param value The value of that vertex. * @param before An string or array of strings with the names of the vertices before * which this vertex must be visited. * @param after An string or array of strings with the names of the vertex after * which this vertex must be visited. * */ DAG.prototype.addEdges = function(name, value, before, after) { var i; this.map(name, value); if (before) { if (typeof before === 'string') { this.addEdge(name, before); } else { for (i = 0; i < before.length; i++) { this.addEdge(name, before[i]); } } } if (after) { if (typeof after === 'string') { this.addEdge(after, name); } else { for (i = 0; i < after.length; i++) { this.addEdge(after[i], name); } } } }; __exports__["default"] = DAG; }); enifed("dag-map.umd", ["./dag-map"], function(__dependency1__) { "use strict"; var DAG = __dependency1__["default"]; /* global define:true module:true window: true */ if (typeof enifed === 'function' && enifed.amd) { enifed(function() { return DAG; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports = DAG; } else if (typeof this !== 'undefined') { this['DAG'] = DAG; } }); enifed('dom-helper', ['exports', './htmlbars-runtime/morph', './morph-attr', './dom-helper/build-html-dom', './dom-helper/classes', './dom-helper/prop'], function (exports, Morph, AttrMorph, build_html_dom, classes, prop) { 'use strict'; var doc = typeof document === "undefined" ? false : document; var deletesBlankTextNodes = doc && (function (document) { var element = document.createElement("div"); element.appendChild(document.createTextNode("")); var clonedElement = element.cloneNode(true); return clonedElement.childNodes.length === 0; })(doc); var ignoresCheckedAttribute = doc && (function (document) { var element = document.createElement("input"); element.setAttribute("checked", "checked"); var clonedElement = element.cloneNode(false); return !clonedElement.checked; })(doc); var canRemoveSvgViewBoxAttribute = doc && (doc.createElementNS ? (function (document) { var element = document.createElementNS(build_html_dom.svgNamespace, "svg"); element.setAttribute("viewBox", "0 0 100 100"); element.removeAttribute("viewBox"); return !element.getAttribute("viewBox"); })(doc) : true); var canClone = doc && (function (document) { var element = document.createElement("div"); element.appendChild(document.createTextNode(" ")); element.appendChild(document.createTextNode(" ")); var clonedElement = element.cloneNode(true); return clonedElement.childNodes[0].nodeValue === " "; })(doc); // This is not the namespace of the element, but of // the elements inside that elements. function interiorNamespace(element) { if (element && element.namespaceURI === build_html_dom.svgNamespace && !build_html_dom.svgHTMLIntegrationPoints[element.tagName]) { return build_html_dom.svgNamespace; } else { return null; } } // The HTML spec allows for "omitted start tags". These tags are optional // when their intended child is the first thing in the parent tag. For // example, this is a tbody start tag: // // // // // // The tbody may be omitted, and the browser will accept and render: // //
// // // However, the omitted start tag will still be added to the DOM. Here // we test the string and context to see if the browser is about to // perform this cleanup. // // http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags // describes which tags are omittable. The spec for tbody and colgroup // explains this behavior: // // http://www.whatwg.org/specs/web-apps/current-work/multipage/tables.html#the-tbody-element // http://www.whatwg.org/specs/web-apps/current-work/multipage/tables.html#the-colgroup-element // var omittedStartTagChildTest = /<([\w:]+)/; function detectOmittedStartTag(string, contextualElement) { // Omitted start tags are only inside table tags. if (contextualElement.tagName === "TABLE") { var omittedStartTagChildMatch = omittedStartTagChildTest.exec(string); if (omittedStartTagChildMatch) { var omittedStartTagChild = omittedStartTagChildMatch[1]; // It is already asserted that the contextual element is a table // and not the proper start tag. Just see if a tag was omitted. return omittedStartTagChild === "tr" || omittedStartTagChild === "col"; } } } function buildSVGDOM(html, dom) { var div = dom.document.createElement("div"); div.innerHTML = "" + html + ""; return div.firstChild.childNodes; } var guid = 1; function ElementMorph(element, dom, namespace) { this.element = element; this.dom = dom; this.namespace = namespace; this.guid = "element" + guid++; this.state = {}; this.isDirty = true; } // renderAndCleanup calls `clear` on all items in the morph map // just before calling `destroy` on the morph. // // As a future refactor this could be changed to set the property // back to its original/default value. ElementMorph.prototype.clear = function () {}; ElementMorph.prototype.destroy = function () { this.element = null; this.dom = null; }; /* * A class wrapping DOM functions to address environment compatibility, * namespaces, contextual elements for morph un-escaped content * insertion. * * When entering a template, a DOMHelper should be passed: * * template(context, { hooks: hooks, dom: new DOMHelper() }); * * TODO: support foreignObject as a passed contextual element. It has * a namespace (svg) that does not match its internal namespace * (xhtml). * * @class DOMHelper * @constructor * @param {HTMLDocument} _document The document DOM methods are proxied to */ function DOMHelper(_document) { this.document = _document || document; if (!this.document) { throw new Error("A document object must be passed to the DOMHelper, or available on the global scope"); } this.canClone = canClone; this.namespace = null; } var prototype = DOMHelper.prototype; prototype.constructor = DOMHelper; prototype.getElementById = function (id, rootNode) { rootNode = rootNode || this.document; return rootNode.getElementById(id); }; prototype.insertBefore = function (element, childElement, referenceChild) { return element.insertBefore(childElement, referenceChild); }; prototype.appendChild = function (element, childElement) { return element.appendChild(childElement); }; prototype.childAt = function (element, indices) { var child = element; for (var i = 0; i < indices.length; i++) { child = child.childNodes.item(indices[i]); } return child; }; // Note to a Fellow Implementor: // Ahh, accessing a child node at an index. Seems like it should be so simple, // doesn't it? Unfortunately, this particular method has caused us a surprising // amount of pain. As you'll note below, this method has been modified to walk // the linked list of child nodes rather than access the child by index // directly, even though there are two (2) APIs in the DOM that do this for us. // If you're thinking to yourself, "What an oversight! What an opportunity to // optimize this code!" then to you I say: stop! For I have a tale to tell. // // First, this code must be compatible with simple-dom for rendering on the // server where there is no real DOM. Previously, we accessed a child node // directly via `element.childNodes[index]`. While we *could* in theory do a // full-fidelity simulation of a live `childNodes` array, this is slow, // complicated and error-prone. // // "No problem," we thought, "we'll just use the similar // `childNodes.item(index)` API." Then, we could just implement our own `item` // method in simple-dom and walk the child node linked list there, allowing // us to retain the performance advantages of the (surely optimized) `item()` // API in the browser. // // Unfortunately, an enterprising soul named Samy Alzahrani discovered that in // IE8, accessing an item out-of-bounds via `item()` causes an exception where // other browsers return null. This necessitated a... check of // `childNodes.length`, bringing us back around to having to support a // full-fidelity `childNodes` array! // // Worst of all, Kris Selden investigated how browsers are actualy implemented // and discovered that they're all linked lists under the hood anyway. Accessing // `childNodes` requires them to allocate a new live collection backed by that // linked list, which is itself a rather expensive operation. Our assumed // optimization had backfired! That is the danger of magical thinking about // the performance of native implementations. // // And this, my friends, is why the following implementation just walks the // linked list, as surprised as that may make you. Please ensure you understand // the above before changing this and submitting a PR. // // Tom Dale, January 18th, 2015, Portland OR prototype.childAtIndex = function (element, index) { var node = element.firstChild; for (var idx = 0; node && idx < index; idx++) { node = node.nextSibling; } return node; }; prototype.appendText = function (element, text) { return element.appendChild(this.document.createTextNode(text)); }; prototype.setAttribute = function (element, name, value) { element.setAttribute(name, String(value)); }; prototype.getAttribute = function (element, name) { return element.getAttribute(name); }; prototype.setAttributeNS = function (element, namespace, name, value) { element.setAttributeNS(namespace, name, String(value)); }; prototype.getAttributeNS = function (element, namespace, name) { return element.getAttributeNS(namespace, name); }; if (canRemoveSvgViewBoxAttribute) { prototype.removeAttribute = function (element, name) { element.removeAttribute(name); }; } else { prototype.removeAttribute = function (element, name) { if (element.tagName === "svg" && name === "viewBox") { element.setAttribute(name, null); } else { element.removeAttribute(name); } }; } prototype.setPropertyStrict = function (element, name, value) { if (value === undefined) { value = null; } if (value === null && (name === "value" || name === "type" || name === "src")) { value = ""; } element[name] = value; }; prototype.getPropertyStrict = function (element, name) { return element[name]; }; prototype.setProperty = function (element, name, value, namespace) { var lowercaseName = name.toLowerCase(); if (element.namespaceURI === build_html_dom.svgNamespace || lowercaseName === "style") { if (prop.isAttrRemovalValue(value)) { element.removeAttribute(name); } else { if (namespace) { element.setAttributeNS(namespace, name, value); } else { element.setAttribute(name, value); } } } else { var normalized = prop.normalizeProperty(element, name); if (normalized) { element[normalized] = value; } else { if (prop.isAttrRemovalValue(value)) { element.removeAttribute(name); } else { if (namespace && element.setAttributeNS) { element.setAttributeNS(namespace, name, value); } else { element.setAttribute(name, value); } } } } }; if (doc && doc.createElementNS) { // Only opt into namespace detection if a contextualElement // is passed. prototype.createElement = function (tagName, contextualElement) { var namespace = this.namespace; if (contextualElement) { if (tagName === "svg") { namespace = build_html_dom.svgNamespace; } else { namespace = interiorNamespace(contextualElement); } } if (namespace) { return this.document.createElementNS(namespace, tagName); } else { return this.document.createElement(tagName); } }; prototype.setAttributeNS = function (element, namespace, name, value) { element.setAttributeNS(namespace, name, String(value)); }; } else { prototype.createElement = function (tagName) { return this.document.createElement(tagName); }; prototype.setAttributeNS = function (element, namespace, name, value) { element.setAttribute(name, String(value)); }; } prototype.addClasses = classes.addClasses; prototype.removeClasses = classes.removeClasses; prototype.setNamespace = function (ns) { this.namespace = ns; }; prototype.detectNamespace = function (element) { this.namespace = interiorNamespace(element); }; prototype.createDocumentFragment = function () { return this.document.createDocumentFragment(); }; prototype.createTextNode = function (text) { return this.document.createTextNode(text); }; prototype.createComment = function (text) { return this.document.createComment(text); }; prototype.repairClonedNode = function (element, blankChildTextNodes, isChecked) { if (deletesBlankTextNodes && blankChildTextNodes.length > 0) { for (var i = 0, len = blankChildTextNodes.length; i < len; i++) { var textNode = this.document.createTextNode(""), offset = blankChildTextNodes[i], before = this.childAtIndex(element, offset); if (before) { element.insertBefore(textNode, before); } else { element.appendChild(textNode); } } } if (ignoresCheckedAttribute && isChecked) { element.setAttribute("checked", "checked"); } }; prototype.cloneNode = function (element, deep) { var clone = element.cloneNode(!!deep); return clone; }; prototype.AttrMorphClass = AttrMorph['default']; prototype.createAttrMorph = function (element, attrName, namespace) { return new this.AttrMorphClass(element, attrName, this, namespace); }; prototype.ElementMorphClass = ElementMorph; prototype.createElementMorph = function (element, namespace) { return new this.ElementMorphClass(element, this, namespace); }; prototype.createUnsafeAttrMorph = function (element, attrName, namespace) { var morph = this.createAttrMorph(element, attrName, namespace); morph.escaped = false; return morph; }; prototype.MorphClass = Morph['default']; prototype.createMorph = function (parent, start, end, contextualElement) { if (contextualElement && contextualElement.nodeType === 11) { throw new Error("Cannot pass a fragment as the contextual element to createMorph"); } if (!contextualElement && parent && parent.nodeType === 1) { contextualElement = parent; } var morph = new this.MorphClass(this, contextualElement); morph.firstNode = start; morph.lastNode = end; return morph; }; prototype.createFragmentMorph = function (contextualElement) { if (contextualElement && contextualElement.nodeType === 11) { throw new Error("Cannot pass a fragment as the contextual element to createMorph"); } var fragment = this.createDocumentFragment(); return Morph['default'].create(this, contextualElement, fragment); }; prototype.replaceContentWithMorph = function (element) { var firstChild = element.firstChild; if (!firstChild) { var comment = this.createComment(""); this.appendChild(element, comment); return Morph['default'].create(this, element, comment); } else { var morph = Morph['default'].attach(this, element, firstChild, element.lastChild); morph.clear(); return morph; } }; prototype.createUnsafeMorph = function (parent, start, end, contextualElement) { var morph = this.createMorph(parent, start, end, contextualElement); morph.parseTextAsHTML = true; return morph; }; // This helper is just to keep the templates good looking, // passing integers instead of element references. prototype.createMorphAt = function (parent, startIndex, endIndex, contextualElement) { var single = startIndex === endIndex; var start = this.childAtIndex(parent, startIndex); var end = single ? start : this.childAtIndex(parent, endIndex); return this.createMorph(parent, start, end, contextualElement); }; prototype.createUnsafeMorphAt = function (parent, startIndex, endIndex, contextualElement) { var morph = this.createMorphAt(parent, startIndex, endIndex, contextualElement); morph.parseTextAsHTML = true; return morph; }; prototype.insertMorphBefore = function (element, referenceChild, contextualElement) { var insertion = this.document.createComment(""); element.insertBefore(insertion, referenceChild); return this.createMorph(element, insertion, insertion, contextualElement); }; prototype.appendMorph = function (element, contextualElement) { var insertion = this.document.createComment(""); element.appendChild(insertion); return this.createMorph(element, insertion, insertion, contextualElement); }; prototype.insertBoundary = function (fragment, index) { // this will always be null or firstChild var child = index === null ? null : this.childAtIndex(fragment, index); this.insertBefore(fragment, this.createTextNode(""), child); }; prototype.parseHTML = function (html, contextualElement) { var childNodes; if (interiorNamespace(contextualElement) === build_html_dom.svgNamespace) { childNodes = buildSVGDOM(html, this); } else { var nodes = build_html_dom.buildHTMLDOM(html, contextualElement, this); if (detectOmittedStartTag(html, contextualElement)) { var node = nodes[0]; while (node && node.nodeType !== 1) { node = node.nextSibling; } childNodes = node.childNodes; } else { childNodes = nodes; } } // Copy node list to a fragment. var fragment = this.document.createDocumentFragment(); if (childNodes && childNodes.length > 0) { var currentNode = childNodes[0]; // We prepend an '; } catch (e) {} finally { tableNeedsInnerHTMLFix = tableInnerHTMLTestElement.childNodes.length === 0; } if (tableNeedsInnerHTMLFix) { tagNamesRequiringInnerHTMLFix = { colgroup: ['table'], table: [], tbody: ['table'], tfoot: ['table'], thead: ['table'], tr: ['table', 'tbody'] }; } // IE 8 doesn't allow setting innerHTML on a select tag. Detect this and // add it to the list of corrected tags. // var selectInnerHTMLTestElement = document.createElement('select'); selectInnerHTMLTestElement.innerHTML = ''; if (!selectInnerHTMLTestElement.childNodes[0]) { tagNamesRequiringInnerHTMLFix = tagNamesRequiringInnerHTMLFix || {}; tagNamesRequiringInnerHTMLFix.select = []; } return tagNamesRequiringInnerHTMLFix; })(doc); function scriptSafeInnerHTML(element, html) { // without a leading text node, IE will drop a leading script tag. html = '­' + html; element.innerHTML = html; var nodes = element.childNodes; // Look for ­ to remove it. var shyElement = nodes[0]; while (shyElement.nodeType === 1 && !shyElement.nodeName) { shyElement = shyElement.firstChild; } // At this point it's the actual unicode character. if (shyElement.nodeType === 3 && shyElement.nodeValue.charAt(0) === '­') { var newValue = shyElement.nodeValue.slice(1); if (newValue.length) { shyElement.nodeValue = shyElement.nodeValue.slice(1); } else { shyElement.parentNode.removeChild(shyElement); } } return nodes; } function buildDOMWithFix(html, contextualElement) { var tagName = contextualElement.tagName; // Firefox versions < 11 do not have support for element.outerHTML. var outerHTML = contextualElement.outerHTML || new XMLSerializer().serializeToString(contextualElement); if (!outerHTML) { throw 'Can\'t set innerHTML on ' + tagName + ' in this browser'; } html = fixSelect(html, contextualElement); var wrappingTags = tagNamesRequiringInnerHTMLFix[tagName.toLowerCase()]; var startTag = outerHTML.match(new RegExp('<' + tagName + '([^>]*)>', 'i'))[0]; var endTag = ''; var wrappedHTML = [startTag, html, endTag]; var i = wrappingTags.length; var wrappedDepth = 1 + i; while (i--) { wrappedHTML.unshift('<' + wrappingTags[i] + '>'); wrappedHTML.push(''); } var wrapper = document.createElement('div'); scriptSafeInnerHTML(wrapper, wrappedHTML.join('')); var element = wrapper; while (wrappedDepth--) { element = element.firstChild; while (element && element.nodeType !== 1) { element = element.nextSibling; } } while (element && element.tagName !== tagName) { element = element.nextSibling; } return element ? element.childNodes : []; } var buildDOM; if (needsShy) { buildDOM = function buildDOM(html, contextualElement, dom) { html = fixSelect(html, contextualElement); contextualElement = dom.cloneNode(contextualElement, false); scriptSafeInnerHTML(contextualElement, html); return contextualElement.childNodes; }; } else { buildDOM = function buildDOM(html, contextualElement, dom) { html = fixSelect(html, contextualElement); contextualElement = dom.cloneNode(contextualElement, false); contextualElement.innerHTML = html; return contextualElement.childNodes; }; } function fixSelect(html, contextualElement) { if (contextualElement.tagName === 'SELECT') { html = '' + html; } return html; } var buildIESafeDOM; if (tagNamesRequiringInnerHTMLFix || movesWhitespace) { buildIESafeDOM = function buildIESafeDOM(html, contextualElement, dom) { // Make a list of the leading text on script nodes. Include // script tags without any whitespace for easier processing later. var spacesBefore = []; var spacesAfter = []; if (typeof html === 'string') { html = html.replace(/(\s*)()(\s*)/g, function (match, tag, spaces) { spacesAfter.push(spaces); return tag; }); } // Fetch nodes var nodes; if (tagNamesRequiringInnerHTMLFix[contextualElement.tagName.toLowerCase()]) { // buildDOMWithFix uses string wrappers for problematic innerHTML. nodes = buildDOMWithFix(html, contextualElement); } else { nodes = buildDOM(html, contextualElement, dom); } // Build a list of script tags, the nodes themselves will be // mutated as we add test nodes. var i, j, node, nodeScriptNodes; var scriptNodes = []; for (i = 0; i < nodes.length; i++) { node = nodes[i]; if (node.nodeType !== 1) { continue; } if (node.tagName === 'SCRIPT') { scriptNodes.push(node); } else { nodeScriptNodes = node.getElementsByTagName('script'); for (j = 0; j < nodeScriptNodes.length; j++) { scriptNodes.push(nodeScriptNodes[j]); } } } // Walk the script tags and put back their leading text nodes. var scriptNode, textNode, spaceBefore, spaceAfter; for (i = 0; i < scriptNodes.length; i++) { scriptNode = scriptNodes[i]; spaceBefore = spacesBefore[i]; if (spaceBefore && spaceBefore.length > 0) { textNode = dom.document.createTextNode(spaceBefore); scriptNode.parentNode.insertBefore(textNode, scriptNode); } spaceAfter = spacesAfter[i]; if (spaceAfter && spaceAfter.length > 0) { textNode = dom.document.createTextNode(spaceAfter); scriptNode.parentNode.insertBefore(textNode, scriptNode.nextSibling); } } return nodes; }; } else { buildIESafeDOM = buildDOM; } var buildHTMLDOM; if (needsIntegrationPointFix) { buildHTMLDOM = function buildHTMLDOM(html, contextualElement, dom) { if (svgHTMLIntegrationPoints[contextualElement.tagName]) { return buildIESafeDOM(html, document.createElement('div'), dom); } else { return buildIESafeDOM(html, contextualElement, dom); } }; } else { buildHTMLDOM = buildIESafeDOM; } exports.svgHTMLIntegrationPoints = svgHTMLIntegrationPoints; exports.svgNamespace = svgNamespace; exports.buildHTMLDOM = buildHTMLDOM; }); enifed('dom-helper/classes', ['exports'], function (exports) { 'use strict'; var doc = typeof document === 'undefined' ? false : document; // PhantomJS has a broken classList. See https://github.com/ariya/phantomjs/issues/12782 var canClassList = doc && (function () { var d = document.createElement('div'); if (!d.classList) { return false; } d.classList.add('boo'); d.classList.add('boo', 'baz'); return d.className === 'boo baz'; })(); function buildClassList(element) { var classString = element.getAttribute('class') || ''; return classString !== '' && classString !== ' ' ? classString.split(' ') : []; } function intersect(containingArray, valuesArray) { var containingIndex = 0; var containingLength = containingArray.length; var valuesIndex = 0; var valuesLength = valuesArray.length; var intersection = new Array(valuesLength); // TODO: rewrite this loop in an optimal manner for (; containingIndex < containingLength; containingIndex++) { valuesIndex = 0; for (; valuesIndex < valuesLength; valuesIndex++) { if (valuesArray[valuesIndex] === containingArray[containingIndex]) { intersection[valuesIndex] = containingIndex; break; } } } return intersection; } function addClassesViaAttribute(element, classNames) { var existingClasses = buildClassList(element); var indexes = intersect(existingClasses, classNames); var didChange = false; for (var i = 0, l = classNames.length; i < l; i++) { if (indexes[i] === undefined) { didChange = true; existingClasses.push(classNames[i]); } } if (didChange) { element.setAttribute('class', existingClasses.length > 0 ? existingClasses.join(' ') : ''); } } function removeClassesViaAttribute(element, classNames) { var existingClasses = buildClassList(element); var indexes = intersect(classNames, existingClasses); var didChange = false; var newClasses = []; for (var i = 0, l = existingClasses.length; i < l; i++) { if (indexes[i] === undefined) { newClasses.push(existingClasses[i]); } else { didChange = true; } } if (didChange) { element.setAttribute('class', newClasses.length > 0 ? newClasses.join(' ') : ''); } } var addClasses, removeClasses; if (canClassList) { addClasses = function addClasses(element, classNames) { if (element.classList) { if (classNames.length === 1) { element.classList.add(classNames[0]); } else if (classNames.length === 2) { element.classList.add(classNames[0], classNames[1]); } else { element.classList.add.apply(element.classList, classNames); } } else { addClassesViaAttribute(element, classNames); } }; removeClasses = function removeClasses(element, classNames) { if (element.classList) { if (classNames.length === 1) { element.classList.remove(classNames[0]); } else if (classNames.length === 2) { element.classList.remove(classNames[0], classNames[1]); } else { element.classList.remove.apply(element.classList, classNames); } } else { removeClassesViaAttribute(element, classNames); } }; } else { addClasses = addClassesViaAttribute; removeClasses = removeClassesViaAttribute; } exports.addClasses = addClasses; exports.removeClasses = removeClasses; }); enifed('dom-helper/prop', ['exports'], function (exports) { 'use strict'; exports.isAttrRemovalValue = isAttrRemovalValue; exports.normalizeProperty = normalizeProperty; function isAttrRemovalValue(value) { return value === null || value === undefined; } // TODO should this be an o_create kind of thing? var propertyCaches = {};function normalizeProperty(element, attrName) { var tagName = element.tagName; var key; var cache = propertyCaches[tagName]; if (!cache) { // TODO should this be an o_create kind of thing? cache = {}; for (key in element) { cache[key.toLowerCase()] = key; } propertyCaches[tagName] = cache; } // presumes that the attrName has been lowercased. return cache[attrName]; } exports.propertyCaches = propertyCaches; }); enifed('ember-application', ['ember-metal/core', 'ember-runtime/system/lazy_load', 'ember-application/system/resolver', 'ember-application/system/application', 'ember-application/ext/controller'], function (Ember, lazy_load, DefaultResolver, Application) { 'use strict'; Ember['default'].Application = Application['default']; Ember['default'].Resolver = DefaultResolver.Resolver; Ember['default'].DefaultResolver = DefaultResolver['default']; lazy_load.runLoadHooks('Ember.Application', Application['default']); }); enifed('ember-application/ext/controller', ['exports', 'ember-metal/core', 'ember-metal/property_get', 'ember-metal/error', 'ember-metal/utils', 'ember-metal/computed', 'ember-runtime/mixins/controller', 'ember-routing/system/controller_for'], function (exports, Ember, property_get, EmberError, utils, computed, ControllerMixin, controllerFor) { 'use strict'; /** @module ember @submodule ember-application */ function verifyNeedsDependencies(controller, container, needs) { var dependency, i, l; var missing = []; for (i = 0, l = needs.length; i < l; i++) { dependency = needs[i]; Ember['default'].assert(utils.inspect(controller) + "#needs must not specify dependencies with periods in their names (" + dependency + ")", dependency.indexOf(".") === -1); if (dependency.indexOf(":") === -1) { dependency = "controller:" + dependency; } // Structure assert to still do verification but not string concat in production if (!container._registry.has(dependency)) { missing.push(dependency); } } if (missing.length) { throw new EmberError['default'](utils.inspect(controller) + " needs [ " + missing.join(", ") + " ] but " + (missing.length > 1 ? "they" : "it") + " could not be found"); } } var defaultControllersComputedProperty = computed.computed(function () { var controller = this; return { needs: property_get.get(controller, "needs"), container: property_get.get(controller, "container"), unknownProperty: function (controllerName) { var needs = this.needs; var dependency, i, l; for (i = 0, l = needs.length; i < l; i++) { dependency = needs[i]; if (dependency === controllerName) { return this.container.lookup("controller:" + controllerName); } } var errorMessage = utils.inspect(controller) + "#needs does not include `" + controllerName + "`. To access the " + controllerName + " controller from " + utils.inspect(controller) + ", " + utils.inspect(controller) + " should have a `needs` property that is an array of the controllers it has access to."; throw new ReferenceError(errorMessage); }, setUnknownProperty: function (key, value) { throw new Error("You cannot overwrite the value of `controllers." + key + "` of " + utils.inspect(controller)); } }; }); /** @class ControllerMixin @namespace Ember */ ControllerMixin['default'].reopen({ concatenatedProperties: ["needs"], /** An array of other controller objects available inside instances of this controller via the `controllers` property: For example, when you define a controller: ```javascript App.CommentsController = Ember.ArrayController.extend({ needs: ['post'] }); ``` The application's single instance of these other controllers are accessible by name through the `controllers` property: ```javascript this.get('controllers.post'); // instance of App.PostController ``` Given that you have a nested controller (nested resource): ```javascript App.CommentsNewController = Ember.ObjectController.extend({ }); ``` When you define a controller that requires access to a nested one: ```javascript App.IndexController = Ember.ObjectController.extend({ needs: ['commentsNew'] }); ``` You will be able to get access to it: ```javascript this.get('controllers.commentsNew'); // instance of App.CommentsNewController ``` This is only available for singleton controllers. @property {Array} needs @default [] */ needs: [], init: function () { var needs = property_get.get(this, "needs"); var length = property_get.get(needs, "length"); if (length > 0) { Ember['default'].assert(" `" + utils.inspect(this) + " specifies `needs`, but does " + "not have a container. Please ensure this controller was " + "instantiated with a container.", this.container || this.controllers !== defaultControllersComputedProperty); if (this.container) { verifyNeedsDependencies(this, this.container, needs); } // if needs then initialize controllers proxy property_get.get(this, "controllers"); } this._super.apply(this, arguments); }, /** @method controllerFor @see {Ember.Route#controllerFor} @deprecated Use `needs` instead */ controllerFor: function (controllerName) { Ember['default'].deprecate("Controller#controllerFor is deprecated, please use Controller#needs instead"); return controllerFor['default'](property_get.get(this, "container"), controllerName); }, /** Stores the instances of other controllers available from within this controller. Any controller listed by name in the `needs` property will be accessible by name through this property. ```javascript App.CommentsController = Ember.ArrayController.extend({ needs: ['post'], postTitle: function() { var currentPost = this.get('controllers.post'); // instance of App.PostController return currentPost.get('title'); }.property('controllers.post.title') }); ``` @see {Ember.ControllerMixin#needs} @property {Object} controllers @default null */ controllers: defaultControllersComputedProperty }); exports['default'] = ControllerMixin['default']; }); enifed('ember-application/system/application-instance', ['exports', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-runtime/system/object', 'ember-metal/run_loop', 'ember-metal/computed', 'container/registry'], function (exports, property_get, property_set, EmberObject, run, computed, Registry) { 'use strict'; /** @module ember @submodule ember-application @private */ exports['default'] = EmberObject['default'].extend({ /** The application instance's container. The container stores all of the instance-specific state for this application run. @property {Ember.Container} container */ container: null, /** The application's registry. The registry contains the classes, templates, and other code that makes up the application. @property {Ember.Registry} registry */ applicationRegistry: null, /** The registry for this application instance. It should use the `applicationRegistry` as a fallback. @property {Ember.Registry} registry */ registry: null, /** The DOM events for which the event dispatcher should listen. By default, the application's `Ember.EventDispatcher` listens for a set of standard DOM events, such as `mousedown` and `keyup`, and delegates them to your application's `Ember.View` instances. @private @property {Object} customEvents */ customEvents: null, /** The root DOM element of the Application as an element or a [jQuery-compatible selector string](http://api.jquery.com/category/selectors/). @private @property {String|DOMElement} rootElement */ rootElement: null, init: function () { this._super.apply(this, arguments); // Create a per-instance registry that will use the application's registry // as a fallback for resolving registrations. this.registry = new Registry['default']({ fallback: this.applicationRegistry, resolver: this.applicationRegistry.resolver }); this.registry.normalizeFullName = this.applicationRegistry.normalizeFullName; this.registry.makeToString = this.applicationRegistry.makeToString; // Create a per-instance container from the instance's registry this.container = this.registry.container(); // Register this instance in the per-instance registry. // // Why do we need to register the instance in the first place? // Because we need a good way for the root route (a.k.a ApplicationRoute) // to notify us when it has created the root-most view. That view is then // appended to the rootElement, in the case of apps, to the fixture harness // in tests, or rendered to a string in the case of FastBoot. this.registry.register("-application-instance:main", this, { instantiate: false }); }, router: computed.computed(function () { return this.container.lookup("router:main"); }).readOnly(), /** Instantiates and sets up the router, specifically overriding the default location. This is useful for manually starting the app in FastBoot or testing environments, where trying to modify the URL would be inappropriate. @param options @private */ overrideRouterLocation: function (options) { var location = options && options.location; var router = property_get.get(this, "router"); if (location) { property_set.set(router, "location", location); } }, /** This hook is called by the root-most Route (a.k.a. the ApplicationRoute) when it has finished creating the root View. By default, we simply take the view and append it to the `rootElement` specified on the Application. In cases like FastBoot and testing, we can override this hook and implement custom behavior, such as serializing to a string and sending over an HTTP socket rather than appending to DOM. @param view {Ember.View} the root-most view @private */ didCreateRootView: function (view) { view.appendTo(this.rootElement); }, /** Tells the router to start routing. The router will ask the location for the current URL of the page to determine the initial URL to start routing to. To start the app at a specific URL, call `handleURL` instead. @private */ startRouting: function () { var router = property_get.get(this, "router"); var isModuleBasedResolver = !!this.registry.resolver.moduleBasedResolver; router.startRouting(isModuleBasedResolver); this._didSetupRouter = true; }, /** @private Sets up the router, initializing the child router and configuring the location before routing begins. Because setup should only occur once, multiple calls to `setupRouter` beyond the first call have no effect. */ setupRouter: function () { if (this._didSetupRouter) { return; } this._didSetupRouter = true; var router = property_get.get(this, "router"); var isModuleBasedResolver = !!this.registry.resolver.moduleBasedResolver; router.setupRouter(isModuleBasedResolver); }, /** Directs the router to route to a particular URL. This is useful in tests, for example, to tell the app to start at a particular URL. Ensure that you have called `setupRouter()` before calling this method. @param url {String} the URL the router should route to @private */ handleURL: function (url) { var router = property_get.get(this, "router"); this.setupRouter(); return router.handleURL(url); }, /** @private */ setupEventDispatcher: function () { var dispatcher = this.container.lookup("event_dispatcher:main"); dispatcher.setup(this.customEvents, this.rootElement); return dispatcher; }, /** @private */ willDestroy: function () { this._super.apply(this, arguments); run['default'](this.container, "destroy"); } }); }); enifed('ember-application/system/application', ['exports', 'dag-map', 'container/registry', 'ember-metal', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-runtime/system/lazy_load', 'ember-runtime/system/namespace', 'ember-runtime/mixins/deferred', 'ember-application/system/resolver', 'ember-metal/platform/create', 'ember-metal/run_loop', 'ember-metal/utils', 'ember-runtime/controllers/controller', 'ember-metal/enumerable_utils', 'ember-runtime/controllers/object_controller', 'ember-runtime/controllers/array_controller', 'ember-metal-views/renderer', 'ember-htmlbars/system/dom-helper', 'ember-views/views/select', 'ember-routing-views/views/outlet', 'ember-views/views/view', 'ember-views/system/event_dispatcher', 'ember-views/system/jquery', 'ember-routing/system/route', 'ember-routing/system/router', 'ember-routing/location/hash_location', 'ember-routing/location/history_location', 'ember-routing/location/auto_location', 'ember-routing/location/none_location', 'ember-routing/system/cache', 'ember-application/system/application-instance', 'ember-views/views/text_field', 'ember-views/views/text_area', 'ember-views/views/checkbox', 'ember-views/views/legacy_each_view', 'ember-routing-views/views/link', 'ember-routing/services/routing', 'ember-extension-support/container_debug_adapter', 'ember-metal/environment'], function (exports, DAG, Registry, Ember, property_get, property_set, lazy_load, Namespace, DeferredMixin, DefaultResolver, create, run, utils, Controller, EnumerableUtils, ObjectController, ArrayController, Renderer, DOMHelper, SelectView, outlet, EmberView, EventDispatcher, jQuery, Route, Router, HashLocation, HistoryLocation, AutoLocation, NoneLocation, BucketCache, ApplicationInstance, TextField, TextArea, Checkbox, LegacyEachView, LinkToComponent, RoutingService, ContainerDebugAdapter, environment) { 'use strict'; /** @module ember @submodule ember-application */ function props(obj) { var properties = []; for (var key in obj) { properties.push(key); } return properties; } var librariesRegistered = false; /** An instance of `Ember.Application` is the starting point for every Ember application. It helps to instantiate, initialize and coordinate the many objects that make up your app. Each Ember app has one and only one `Ember.Application` object. In fact, the very first thing you should do in your application is create the instance: ```javascript window.App = Ember.Application.create(); ``` Typically, the application object is the only global variable. All other classes in your app should be properties on the `Ember.Application` instance, which highlights its first role: a global namespace. For example, if you define a view class, it might look like this: ```javascript App.MyView = Ember.View.extend(); ``` By default, calling `Ember.Application.create()` will automatically initialize your application by calling the `Ember.Application.initialize()` method. If you need to delay initialization, you can call your app's `deferReadiness()` method. When you are ready for your app to be initialized, call its `advanceReadiness()` method. You can define a `ready` method on the `Ember.Application` instance, which will be run by Ember when the application is initialized. Because `Ember.Application` inherits from `Ember.Namespace`, any classes you create will have useful string representations when calling `toString()`. See the `Ember.Namespace` documentation for more information. While you can think of your `Ember.Application` as a container that holds the other classes in your application, there are several other responsibilities going on under-the-hood that you may want to understand. ### Event Delegation Ember uses a technique called _event delegation_. This allows the framework to set up a global, shared event listener instead of requiring each view to do it manually. For example, instead of each view registering its own `mousedown` listener on its associated element, Ember sets up a `mousedown` listener on the `body`. If a `mousedown` event occurs, Ember will look at the target of the event and start walking up the DOM node tree, finding corresponding views and invoking their `mouseDown` method as it goes. `Ember.Application` has a number of default events that it listens for, as well as a mapping from lowercase events to camel-cased view method names. For example, the `keypress` event causes the `keyPress` method on the view to be called, the `dblclick` event causes `doubleClick` to be called, and so on. If there is a bubbling browser event that Ember does not listen for by default, you can specify custom events and their corresponding view method names by setting the application's `customEvents` property: ```javascript var App = Ember.Application.create({ customEvents: { // add support for the paste event paste: 'paste' } }); ``` By default, the application sets up these event listeners on the document body. However, in cases where you are embedding an Ember application inside an existing page, you may want it to set up the listeners on an element inside the body. For example, if only events inside a DOM element with the ID of `ember-app` should be delegated, set your application's `rootElement` property: ```javascript var App = Ember.Application.create({ rootElement: '#ember-app' }); ``` The `rootElement` can be either a DOM element or a jQuery-compatible selector string. Note that *views appended to the DOM outside the root element will not receive events.* If you specify a custom root element, make sure you only append views inside it! To learn more about the advantages of event delegation and the Ember view layer, and a list of the event listeners that are setup by default, visit the [Ember View Layer guide](http://emberjs.com/guides/understanding-ember/the-view-layer/#toc_event-delegation). ### Initializers Libraries on top of Ember can add initializers, like so: ```javascript Ember.Application.initializer({ name: 'api-adapter', initialize: function(container, application) { application.register('api-adapter:main', ApiAdapter); } }); ``` Initializers provide an opportunity to access the container, which organizes the different components of an Ember application. Additionally they provide a chance to access the instantiated application. Beyond being used for libraries, initializers are also a great way to organize dependency injection or setup in your own application. ### Routing In addition to creating your application's router, `Ember.Application` is also responsible for telling the router when to start routing. Transitions between routes can be logged with the `LOG_TRANSITIONS` flag, and more detailed intra-transition logging can be logged with the `LOG_TRANSITIONS_INTERNAL` flag: ```javascript var App = Ember.Application.create({ LOG_TRANSITIONS: true, // basic logging of successful transitions LOG_TRANSITIONS_INTERNAL: true // detailed logging of all routing steps }); ``` By default, the router will begin trying to translate the current URL into application state once the browser emits the `DOMContentReady` event. If you need to defer routing, you can call the application's `deferReadiness()` method. Once routing can begin, call the `advanceReadiness()` method. If there is any setup required before routing begins, you can implement a `ready()` method on your app that will be invoked immediately before routing begins. @class Application @namespace Ember @extends Ember.Namespace */ var Application = Namespace['default'].extend(DeferredMixin['default'], { _suppressDeferredDeprecation: true, /** The root DOM element of the Application. This can be specified as an element or a [jQuery-compatible selector string](http://api.jquery.com/category/selectors/). This is the element that will be passed to the Application's, `eventDispatcher`, which sets up the listeners for event delegation. Every view in your application should be a child of the element you specify here. @property rootElement @type DOMElement @default 'body' */ rootElement: 'body', /** The `Ember.EventDispatcher` responsible for delegating events to this application's views. The event dispatcher is created by the application at initialization time and sets up event listeners on the DOM element described by the application's `rootElement` property. See the documentation for `Ember.EventDispatcher` for more information. @property eventDispatcher @type Ember.EventDispatcher @default null */ eventDispatcher: null, /** The DOM events for which the event dispatcher should listen. By default, the application's `Ember.EventDispatcher` listens for a set of standard DOM events, such as `mousedown` and `keyup`, and delegates them to your application's `Ember.View` instances. If you would like additional bubbling events to be delegated to your views, set your `Ember.Application`'s `customEvents` property to a hash containing the DOM event name as the key and the corresponding view method name as the value. For example: ```javascript var App = Ember.Application.create({ customEvents: { // add support for the paste event paste: 'paste' } }); ``` @property customEvents @type Object @default null */ customEvents: null, /** Whether the application should automatically start routing and render templates to the `rootElement` on DOM ready. While default by true, other environments such as FastBoot or a testing harness can set this property to `false` and control the precise timing and behavior of the boot process. @property autoboot @type Boolean @default true @private */ autoboot: true, init: function () { this._super.apply(this, arguments); if (!this.$) { this.$ = jQuery['default']; } this.buildRegistry(); registerLibraries(); logLibraryVersions(); // Start off the number of deferrals at 1. This will be // decremented by the Application's own `initialize` method. this._readinessDeferrals = 1; this.Router = (this.Router || Router['default']).extend(); this.waitForDOMReady(this.buildDefaultInstance()); }, /** Build and configure the registry for the current application. @private @method buildRegistry @return {Ember.Registry} the configured registry */ buildRegistry: function () { var registry = this.registry = Application.buildRegistry(this); return registry; }, /** Create a container for the current application's registry. @private @method buildInstance @return {Ember.Container} the configured container */ buildInstance: function () { return ApplicationInstance['default'].create({ customEvents: property_get.get(this, 'customEvents'), rootElement: property_get.get(this, 'rootElement'), applicationRegistry: this.registry }); }, buildDefaultInstance: function () { var instance = this.buildInstance(); // For the default instance only, set the view registry to the global // Ember.View.views hash for backwards-compatibility. EmberView['default'].views = instance.container.lookup('-view-registry:main'); // TODO2.0: Legacy support for App.__container__ // and global methods on App that rely on a single, // default instance. this.__deprecatedInstance__ = instance; this.__container__ = instance.container; return instance; }, /** Automatically initialize the application once the DOM has become ready. The initialization itself is scheduled on the actions queue which ensures that application loading finishes before booting. If you are asynchronously loading code, you should call `deferReadiness()` to defer booting, and then call `advanceReadiness()` once all of your code has finished loading. @private @method scheduleInitialize */ waitForDOMReady: function (_instance) { if (!this.$ || this.$.isReady) { run['default'].schedule('actions', this, 'domReady', _instance); } else { this.$().ready(run['default'].bind(this, 'domReady', _instance)); } }, /** Use this to defer readiness until some condition is true. Example: ```javascript var App = Ember.Application.create(); App.deferReadiness(); // Ember.$ is a reference to the jQuery object/function Ember.$.getJSON('/auth-token', function(token) { App.token = token; App.advanceReadiness(); }); ``` This allows you to perform asynchronous setup logic and defer booting your application until the setup has finished. However, if the setup requires a loading UI, it might be better to use the router for this purpose. @method deferReadiness */ deferReadiness: function () { Ember['default'].assert('You must call deferReadiness on an instance of Ember.Application', this instanceof Application); Ember['default'].assert('You cannot defer readiness since the `ready()` hook has already been called.', this._readinessDeferrals > 0); this._readinessDeferrals++; }, /** Call `advanceReadiness` after any asynchronous setup logic has completed. Each call to `deferReadiness` must be matched by a call to `advanceReadiness` or the application will never become ready and routing will not begin. @method advanceReadiness @see {Ember.Application#deferReadiness} */ advanceReadiness: function () { Ember['default'].assert('You must call advanceReadiness on an instance of Ember.Application', this instanceof Application); this._readinessDeferrals--; if (this._readinessDeferrals === 0) { run['default'].once(this, this.didBecomeReady); } }, /** Registers a factory that can be used for dependency injection (with `App.inject`) or for service lookup. Each factory is registered with a full name including two parts: `type:name`. A simple example: ```javascript var App = Ember.Application.create(); App.Orange = Ember.Object.extend(); App.register('fruit:favorite', App.Orange); ``` Ember will resolve factories from the `App` namespace automatically. For example `App.CarsController` will be discovered and returned if an application requests `controller:cars`. An example of registering a controller with a non-standard name: ```javascript var App = Ember.Application.create(); var Session = Ember.Controller.extend(); App.register('controller:session', Session); // The Session controller can now be treated like a normal controller, // despite its non-standard name. App.ApplicationController = Ember.Controller.extend({ needs: ['session'] }); ``` Registered factories are **instantiated** by having `create` called on them. Additionally they are **singletons**, each time they are looked up they return the same instance. Some examples modifying that default behavior: ```javascript var App = Ember.Application.create(); App.Person = Ember.Object.extend(); App.Orange = Ember.Object.extend(); App.Email = Ember.Object.extend(); App.session = Ember.Object.create(); App.register('model:user', App.Person, { singleton: false }); App.register('fruit:favorite', App.Orange); App.register('communication:main', App.Email, { singleton: false }); App.register('session', App.session, { instantiate: false }); ``` @method register @param fullName {String} type:name (e.g., 'model:user') @param factory {Function} (e.g., App.Person) @param options {Object} (optional) disable instantiation or singleton usage **/ register: function () { var _registry; (_registry = this.registry).register.apply(_registry, arguments); }, /** Define a dependency injection onto a specific factory or all factories of a type. When Ember instantiates a controller, view, or other framework component it can attach a dependency to that component. This is often used to provide services to a set of framework components. An example of providing a session object to all controllers: ```javascript var App = Ember.Application.create(); var Session = Ember.Object.extend({ isAuthenticated: false }); // A factory must be registered before it can be injected App.register('session:main', Session); // Inject 'session:main' onto all factories of the type 'controller' // with the name 'session' App.inject('controller', 'session', 'session:main'); App.IndexController = Ember.Controller.extend({ isLoggedIn: Ember.computed.alias('session.isAuthenticated') }); ``` Injections can also be performed on specific factories. ```javascript App.inject(, , ) App.inject('route', 'source', 'source:main') App.inject('route:application', 'email', 'model:email') ``` It is important to note that injections can only be performed on classes that are instantiated by Ember itself. Instantiating a class directly (via `create` or `new`) bypasses the dependency injection system. **Note:** Ember-Data instantiates its models in a unique manner, and consequently injections onto models (or all models) will not work as expected. Injections on models can be enabled by setting `Ember.MODEL_FACTORY_INJECTIONS` to `true`. @method inject @param factoryNameOrType {String} @param property {String} @param injectionName {String} **/ inject: function () { var _registry2; (_registry2 = this.registry).injection.apply(_registry2, arguments); }, /** Calling initialize manually is not supported. Please see Ember.Application#advanceReadiness and Ember.Application#deferReadiness. @private @deprecated @method initialize **/ initialize: function () { Ember['default'].deprecate('Calling initialize manually is not supported. Please see Ember.Application#advanceReadiness and Ember.Application#deferReadiness'); }, /** Initialize the application. This happens automatically. Run any initializers and run the application load hook. These hooks may choose to defer readiness. For example, an authentication hook might want to defer readiness until the auth token has been retrieved. @private @method _initialize */ domReady: function (_instance) { if (this.isDestroyed) { return; } var app = this; this.boot().then(function () { app.runInstanceInitializers(_instance); }); return this; }, boot: function () { if (this._bootPromise) { return this._bootPromise; } var defer = new Ember['default'].RSVP.defer(); this._bootPromise = defer.promise; this._bootResolver = defer; this.runInitializers(this.registry); lazy_load.runLoadHooks('application', this); this.advanceReadiness(); return this._bootPromise; }, /** Reset the application. This is typically used only in tests. It cleans up the application in the following order: 1. Deactivate existing routes 2. Destroy all objects in the container 3. Create a new application container 4. Re-route to the existing url Typical Example: ```javascript var App; run(function() { App = Ember.Application.create(); }); module('acceptance test', { setup: function() { App.reset(); } }); test('first test', function() { // App is freshly reset }); test('second test', function() { // App is again freshly reset }); ``` Advanced Example: Occasionally you may want to prevent the app from initializing during setup. This could enable extra configuration, or enable asserting prior to the app becoming ready. ```javascript var App; run(function() { App = Ember.Application.create(); }); module('acceptance test', { setup: function() { run(function() { App.reset(); App.deferReadiness(); }); } }); test('first test', function() { ok(true, 'something before app is initialized'); run(function() { App.advanceReadiness(); }); ok(true, 'something after app is initialized'); }); ``` @method reset **/ reset: function () { var instance = this.__deprecatedInstance__; this._readinessDeferrals = 1; this._bootPromise = null; this._bootResolver = null; function handleReset() { run['default'](instance, 'destroy'); run['default'].schedule('actions', this, 'domReady', this.buildDefaultInstance()); } run['default'].join(this, handleReset); }, /** @private @method runInitializers */ runInitializers: function (registry) { var App = this; this._runInitializer('initializers', function (name, initializer) { Ember['default'].assert('No application initializer named \'' + name + '\'', !!initializer); initializer.initialize(registry, App); }); }, runInstanceInitializers: function (instance) { this._runInitializer('instanceInitializers', function (name, initializer) { Ember['default'].assert('No instance initializer named \'' + name + '\'', !!initializer); initializer.initialize(instance); }); }, _runInitializer: function (bucketName, cb) { var initializersByName = property_get.get(this.constructor, bucketName); var initializers = props(initializersByName); var graph = new DAG['default'](); var initializer; for (var i = 0; i < initializers.length; i++) { initializer = initializersByName[initializers[i]]; graph.addEdges(initializer.name, initializer, initializer.before, initializer.after); } graph.topsort(function (vertex) { cb(vertex.name, vertex.value); }); }, /** @private @method didBecomeReady */ didBecomeReady: function () { if (this.autoboot) { if (environment['default'].hasDOM) { this.__deprecatedInstance__.setupEventDispatcher(); } this.ready(); // user hook this.__deprecatedInstance__.startRouting(); if (!Ember['default'].testing) { // Eagerly name all classes that are already loaded Ember['default'].Namespace.processAll(); Ember['default'].BOOTED = true; } this.resolve(this); } this._bootResolver.resolve(); }, /** Called when the Application has become ready. The call will be delayed until the DOM has become ready. @event ready */ ready: function () { return this; }, /** @deprecated Use 'Resolver' instead Set this to provide an alternate class to `Ember.DefaultResolver` @property resolver */ resolver: null, /** Set this to provide an alternate class to `Ember.DefaultResolver` @property resolver */ Resolver: null, // This method must be moved to the application instance object willDestroy: function () { this._super.apply(this, arguments); Ember['default'].BOOTED = false; this._bootPromise = null; this._bootResolver = null; this.__deprecatedInstance__.destroy(); }, initializer: function (options) { this.constructor.initializer(options); }, /** @method then @private @deprecated */ then: function () { Ember['default'].deprecate('Do not use `.then` on an instance of Ember.Application. Please use the `.ready` hook instead.', false, { url: 'http://emberjs.com/guides/deprecations/#toc_deprecate-code-then-code-on-ember-application' }); this._super.apply(this, arguments); } }); Application.reopen({ instanceInitializer: function (options) { this.constructor.instanceInitializer(options); } }); Application.reopenClass({ instanceInitializer: buildInitializerMethod('instanceInitializers', 'instance initializer') }); Application.reopenClass({ initializers: create['default'](null), instanceInitializers: create['default'](null), /** Initializer receives an object which has the following attributes: `name`, `before`, `after`, `initialize`. The only required attribute is `initialize`, all others are optional. * `name` allows you to specify under which name the initializer is registered. This must be a unique name, as trying to register two initializers with the same name will result in an error. ```javascript Ember.Application.initializer({ name: 'namedInitializer', initialize: function(container, application) { Ember.debug('Running namedInitializer!'); } }); ``` * `before` and `after` are used to ensure that this initializer is ran prior or after the one identified by the value. This value can be a single string or an array of strings, referencing the `name` of other initializers. An example of ordering initializers, we create an initializer named `first`: ```javascript Ember.Application.initializer({ name: 'first', initialize: function(container, application) { Ember.debug('First initializer!'); } }); // DEBUG: First initializer! ``` We add another initializer named `second`, specifying that it should run after the initializer named `first`: ```javascript Ember.Application.initializer({ name: 'second', after: 'first', initialize: function(container, application) { Ember.debug('Second initializer!'); } }); // DEBUG: First initializer! // DEBUG: Second initializer! ``` Afterwards we add a further initializer named `pre`, this time specifying that it should run before the initializer named `first`: ```javascript Ember.Application.initializer({ name: 'pre', before: 'first', initialize: function(container, application) { Ember.debug('Pre initializer!'); } }); // DEBUG: Pre initializer! // DEBUG: First initializer! // DEBUG: Second initializer! ``` Finally we add an initializer named `post`, specifying it should run after both the `first` and the `second` initializers: ```javascript Ember.Application.initializer({ name: 'post', after: ['first', 'second'], initialize: function(container, application) { Ember.debug('Post initializer!'); } }); // DEBUG: Pre initializer! // DEBUG: First initializer! // DEBUG: Second initializer! // DEBUG: Post initializer! ``` * `initialize` is a callback function that receives two arguments, `container` and `application` on which you can operate. Example of using `container` to preload data into the store: ```javascript Ember.Application.initializer({ name: 'preload-data', initialize: function(container, application) { var store = container.lookup('store:main'); store.pushPayload(preloadedData); } }); ``` Example of using `application` to register an adapter: ```javascript Ember.Application.initializer({ name: 'api-adapter', initialize: function(container, application) { application.register('api-adapter:main', ApiAdapter); } }); ``` @method initializer @param initializer {Object} */ initializer: buildInitializerMethod('initializers', 'initializer'), /** This creates a registry with the default Ember naming conventions. It also configures the registry: * registered views are created every time they are looked up (they are not singletons) * registered templates are not factories; the registered value is returned directly. * the router receives the application as its `namespace` property * all controllers receive the router as their `target` and `controllers` properties * all controllers receive the application as their `namespace` property * the application view receives the application controller as its `controller` property * the application view receives the application template as its `defaultTemplate` property @private @method buildRegistry @static @param {Ember.Application} namespace the application for which to build the registry @return {Ember.Registry} the built registry */ buildRegistry: function (namespace) { var registry = new Registry['default'](); registry.set = property_set.set; registry.resolver = resolverFor(namespace); registry.normalizeFullName = registry.resolver.normalize; registry.describe = registry.resolver.describe; registry.makeToString = registry.resolver.makeToString; registry.optionsForType('component', { singleton: false }); registry.optionsForType('view', { singleton: false }); registry.optionsForType('template', { instantiate: false }); registry.optionsForType('helper', { instantiate: false }); registry.register('application:main', namespace, { instantiate: false }); registry.register('controller:basic', Controller['default'], { instantiate: false }); registry.register('controller:object', ObjectController['default'], { instantiate: false }); registry.register('controller:array', ArrayController['default'], { instantiate: false }); registry.register('renderer:-dom', { create: function () { return new Renderer['default'](new DOMHelper['default']()); } }); registry.injection('view', 'renderer', 'renderer:-dom'); registry.register('view:select', SelectView['default']); registry.register('view:-outlet', outlet.OutletView); registry.register('-view-registry:main', { create: function () { return {}; } }); registry.injection('view', '_viewRegistry', '-view-registry:main'); registry.register('view:toplevel', EmberView['default'].extend()); registry.register('route:basic', Route['default'], { instantiate: false }); registry.register('event_dispatcher:main', EventDispatcher['default']); registry.injection('router:main', 'namespace', 'application:main'); registry.injection('view:-outlet', 'namespace', 'application:main'); registry.register('location:auto', AutoLocation['default']); registry.register('location:hash', HashLocation['default']); registry.register('location:history', HistoryLocation['default']); registry.register('location:none', NoneLocation['default']); registry.injection('controller', 'target', 'router:main'); registry.injection('controller', 'namespace', 'application:main'); registry.register('-bucket-cache:main', BucketCache['default']); registry.injection('router', '_bucketCache', '-bucket-cache:main'); registry.injection('route', '_bucketCache', '-bucket-cache:main'); registry.injection('controller', '_bucketCache', '-bucket-cache:main'); registry.injection('route', 'router', 'router:main'); registry.register('component:-text-field', TextField['default']); registry.register('component:-text-area', TextArea['default']); registry.register('component:-checkbox', Checkbox['default']); registry.register('view:-legacy-each', LegacyEachView['default']); registry.register('component:-link-to', LinkToComponent['default']); // Register the routing service... registry.register('service:-routing', RoutingService['default']); // Then inject the app router into it registry.injection('service:-routing', 'router', 'router:main'); // DEBUGGING registry.register('resolver-for-debugging:main', registry.resolver.__resolver__, { instantiate: false }); registry.injection('container-debug-adapter:main', 'resolver', 'resolver-for-debugging:main'); registry.injection('data-adapter:main', 'containerDebugAdapter', 'container-debug-adapter:main'); // Custom resolver authors may want to register their own ContainerDebugAdapter with this key registry.register('container-debug-adapter:main', ContainerDebugAdapter['default']); return registry; } }); /** This function defines the default lookup rules for container lookups: * templates are looked up on `Ember.TEMPLATES` * other names are looked up on the application after classifying the name. For example, `controller:post` looks up `App.PostController` by default. * if the default lookup fails, look for registered classes on the container This allows the application to register default injections in the container that could be overridden by the normal naming convention. @private @method resolverFor @param {Ember.Namespace} namespace the namespace to look for classes @return {*} the resolved value for a given lookup */ function resolverFor(namespace) { Ember['default'].deprecate('Application.resolver is deprecated in favor of Application.Resolver', !namespace.get('resolver')); var ResolverClass = namespace.get('resolver') || namespace.get('Resolver') || DefaultResolver['default']; var resolver = ResolverClass.create({ namespace: namespace }); function resolve(fullName) { return resolver.resolve(fullName); } resolve.describe = function (fullName) { return resolver.lookupDescription(fullName); }; resolve.makeToString = function (factory, fullName) { return resolver.makeToString(factory, fullName); }; resolve.normalize = function (fullName) { if (resolver.normalize) { return resolver.normalize(fullName); } else { Ember['default'].deprecate('The Resolver should now provide a \'normalize\' function', false); return fullName; } }; resolve.__resolver__ = resolver; return resolve; } function registerLibraries() { if (!librariesRegistered) { librariesRegistered = true; if (environment['default'].hasDOM) { Ember['default'].libraries.registerCoreLibrary('jQuery', jQuery['default']().jquery); } } } function logLibraryVersions() { if (Ember['default'].LOG_VERSION) { // we only need to see this once per Application#init Ember['default'].LOG_VERSION = false; var libs = Ember['default'].libraries._registry; var nameLengths = EnumerableUtils['default'].map(libs, function (item) { return property_get.get(item, 'name.length'); }); var maxNameLength = Math.max.apply(this, nameLengths); Ember['default'].debug('-------------------------------'); for (var i = 0, l = libs.length; i < l; i++) { var lib = libs[i]; var spaces = new Array(maxNameLength - lib.name.length + 1).join(' '); Ember['default'].debug([lib.name, spaces, ' : ', lib.version].join('')); } Ember['default'].debug('-------------------------------'); } } function buildInitializerMethod(bucketName, humanName) { return function (initializer) { // If this is the first initializer being added to a subclass, we are going to reopen the class // to make sure we have a new `initializers` object, which extends from the parent class' using // prototypal inheritance. Without this, attempting to add initializers to the subclass would // pollute the parent class as well as other subclasses. if (this.superclass[bucketName] !== undefined && this.superclass[bucketName] === this[bucketName]) { var attrs = {}; attrs[bucketName] = create['default'](this[bucketName]); this.reopenClass(attrs); } Ember['default'].assert('The ' + humanName + ' \'' + initializer.name + '\' has already been registered', !this[bucketName][initializer.name]); Ember['default'].assert('An ' + humanName + ' cannot be registered without an initialize function', utils.canInvoke(initializer, 'initialize')); Ember['default'].assert('An ' + humanName + ' cannot be registered without a name property', initializer.name !== undefined); this[bucketName][initializer.name] = initializer; }; } exports['default'] = Application; }); enifed('ember-application/system/resolver', ['exports', 'ember-metal/core', 'ember-metal/property_get', 'ember-metal/logger', 'ember-runtime/system/string', 'ember-runtime/system/object', 'ember-runtime/system/namespace', 'ember-htmlbars/helpers', 'ember-application/utils/validate-type', 'ember-metal/dictionary'], function (exports, Ember, property_get, Logger, string, EmberObject, Namespace, helpers, validateType, dictionary) { 'use strict'; /** @module ember @submodule ember-application */ var Resolver = EmberObject['default'].extend({ /** This will be set to the Application instance when it is created. @property namespace */ namespace: null, normalize: null, // required resolve: null, // required parseName: null, // required lookupDescription: null, // required makeToString: null, // required resolveOther: null, // required _logLookup: null // required });exports['default'] = EmberObject['default'].extend({ /** This will be set to the Application instance when it is created. @property namespace */ namespace: null, init: function () { this._parseNameCache = dictionary['default'](null); }, normalize: function (fullName) { var _fullName$split = fullName.split(':', 2); var type = _fullName$split[0]; var name = _fullName$split[1]; Ember['default'].assert('Tried to normalize a container name without a colon (:) in it.' + ' You probably tried to lookup a name that did not contain a type,' + ' a colon, and a name. A proper lookup name would be `view:post`.', fullName.split(':').length === 2); if (type !== 'template') { var result = name; if (result.indexOf('.') > -1) { result = result.replace(/\.(.)/g, function (m) { return m.charAt(1).toUpperCase(); }); } if (name.indexOf('_') > -1) { result = result.replace(/_(.)/g, function (m) { return m.charAt(1).toUpperCase(); }); } return type + ':' + result; } else { return fullName; } }, /** This method is called via the container's resolver method. It parses the provided `fullName` and then looks up and returns the appropriate template or class. @method resolve @param {String} fullName the lookup string @return {Object} the resolved factory */ resolve: function (fullName) { var parsedName = this.parseName(fullName); var resolveMethodName = parsedName.resolveMethodName; var resolved; if (this[resolveMethodName]) { resolved = this[resolveMethodName](parsedName); } resolved = resolved || this.resolveOther(parsedName); if (parsedName.root && parsedName.root.LOG_RESOLVER) { this._logLookup(resolved, parsedName); } if (resolved) { validateType['default'](resolved, parsedName); } return resolved; }, /** Convert the string name of the form 'type:name' to a Javascript object with the parsed aspects of the name broken out. @protected @param {String} fullName the lookup string @method parseName */ parseName: function (fullName) { return this._parseNameCache[fullName] || (this._parseNameCache[fullName] = this._parseName(fullName)); }, _parseName: function (fullName) { var _fullName$split2 = fullName.split(':'); var type = _fullName$split2[0]; var fullNameWithoutType = _fullName$split2[1]; var name = fullNameWithoutType; var namespace = property_get.get(this, 'namespace'); var root = namespace; if (type !== 'template' && name.indexOf('/') !== -1) { var parts = name.split('/'); name = parts[parts.length - 1]; var namespaceName = string.capitalize(parts.slice(0, -1).join('.')); root = Namespace['default'].byName(namespaceName); Ember['default'].assert('You are looking for a ' + name + ' ' + type + ' in the ' + namespaceName + ' namespace, but the namespace could not be found', root); } var resolveMethodName = fullNameWithoutType === 'main' ? 'Main' : string.classify(type); if (!(name && type)) { throw new TypeError('Invalid fullName: `' + fullName + '`, must be of the form `type:name` '); } return { fullName: fullName, type: type, fullNameWithoutType: fullNameWithoutType, name: name, root: root, resolveMethodName: 'resolve' + resolveMethodName }; }, /** Returns a human-readable description for a fullName. Used by the Application namespace in assertions to describe the precise name of the class that Ember is looking for, rather than container keys. @protected @param {String} fullName the lookup string @method lookupDescription */ lookupDescription: function (fullName) { var parsedName = this.parseName(fullName); var description; if (parsedName.type === 'template') { return 'template at ' + parsedName.fullNameWithoutType.replace(/\./g, '/'); } description = parsedName.root + '.' + string.classify(parsedName.name).replace(/\./g, ''); if (parsedName.type !== 'model') { description += string.classify(parsedName.type); } return description; }, makeToString: function (factory, fullName) { return factory.toString(); }, /** Given a parseName object (output from `parseName`), apply the conventions expected by `Ember.Router` @protected @param {Object} parsedName a parseName object with the parsed fullName lookup string @method useRouterNaming */ useRouterNaming: function (parsedName) { parsedName.name = parsedName.name.replace(/\./g, '_'); if (parsedName.name === 'basic') { parsedName.name = ''; } }, /** Look up the template in Ember.TEMPLATES @protected @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveTemplate */ resolveTemplate: function (parsedName) { var templateName = parsedName.fullNameWithoutType.replace(/\./g, '/'); if (Ember['default'].TEMPLATES[templateName]) { return Ember['default'].TEMPLATES[templateName]; } templateName = string.decamelize(templateName); if (Ember['default'].TEMPLATES[templateName]) { return Ember['default'].TEMPLATES[templateName]; } }, /** Lookup the view using `resolveOther` @protected @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveView */ resolveView: function (parsedName) { this.useRouterNaming(parsedName); return this.resolveOther(parsedName); }, /** Lookup the controller using `resolveOther` @protected @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveController */ resolveController: function (parsedName) { this.useRouterNaming(parsedName); return this.resolveOther(parsedName); }, /** Lookup the route using `resolveOther` @protected @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveRoute */ resolveRoute: function (parsedName) { this.useRouterNaming(parsedName); return this.resolveOther(parsedName); }, /** Lookup the model on the Application namespace @protected @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveModel */ resolveModel: function (parsedName) { var className = string.classify(parsedName.name); var factory = property_get.get(parsedName.root, className); if (factory) { return factory; } }, /** Look up the specified object (from parsedName) on the appropriate namespace (usually on the Application) @protected @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveHelper */ resolveHelper: function (parsedName) { return this.resolveOther(parsedName) || helpers['default'][parsedName.fullNameWithoutType]; }, /** Look up the specified object (from parsedName) on the appropriate namespace (usually on the Application) @protected @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveOther */ resolveOther: function (parsedName) { var className = string.classify(parsedName.name) + string.classify(parsedName.type); var factory = property_get.get(parsedName.root, className); if (factory) { return factory; } }, resolveMain: function (parsedName) { var className = string.classify(parsedName.type); return property_get.get(parsedName.root, className); }, /** @method _logLookup @param {Boolean} found @param {Object} parsedName @private */ _logLookup: function (found, parsedName) { var symbol, padding; if (found) { symbol = '[✓]'; } else { symbol = '[ ]'; } if (parsedName.fullName.length > 60) { padding = '.'; } else { padding = new Array(60 - parsedName.fullName.length).join('.'); } Logger['default'].info(symbol, parsedName.fullName, padding, this.lookupDescription(parsedName.fullName)); } }); exports.Resolver = Resolver; }); enifed('ember-application/utils/validate-type', ['exports'], function (exports) { 'use strict'; exports['default'] = validateType; /** @module ember @submodule ember-application */ var VALIDATED_TYPES = { route: ['isRouteFactory', 'Ember.Route'], component: ['isComponentFactory', 'Ember.Component'], view: ['isViewFactory', 'Ember.View'], service: ['isServiceFactory', 'Ember.Service'] }; function validateType(resolvedType, parsedName) { var validationAttributes = VALIDATED_TYPES[parsedName.type]; if (!validationAttributes) { return; } var factoryFlag = validationAttributes[0]; var expectedType = validationAttributes[1]; Ember.assert('Expected ' + parsedName.fullName + ' to resolve to an ' + expectedType + ' but instead it was ' + resolvedType + '.', function () { return resolvedType[factoryFlag]; }); } }); enifed('ember-debug', ['exports', 'ember-metal/core', 'ember-metal/error', 'ember-metal/logger', 'ember-metal/environment'], function (exports, Ember, EmberError, Logger, environment) { 'use strict'; exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags; function isPlainFunction(test) { return typeof test === "function" && test.PrototypeMixin === undefined; } /** Define an assertion that will throw an exception if the condition is not met. Ember build tools will remove any calls to `Ember.assert()` when doing a production build. Example: ```javascript // Test for truthiness Ember.assert('Must pass a valid object', obj); // Fail unconditionally Ember.assert('This code path should never be run'); ``` @method assert @param {String} desc A description of the assertion. This will become the text of the Error thrown if the assertion fails. @param {Boolean|Function} test Must be truthy for the assertion to pass. If falsy, an exception will be thrown. If this is a function, it will be executed and its return value will be used as condition. */ Ember['default'].assert = function (desc, test) { var throwAssertion; if (isPlainFunction(test)) { throwAssertion = !test(); } else { throwAssertion = !test; } if (throwAssertion) { throw new EmberError['default']("Assertion Failed: " + desc); } }; /** Display a warning with the provided message. Ember build tools will remove any calls to `Ember.warn()` when doing a production build. @method warn @param {String} message A warning to display. @param {Boolean} test An optional boolean. If falsy, the warning will be displayed. */ Ember['default'].warn = function (message, test) { if (!test) { Logger['default'].warn("WARNING: " + message); if ("trace" in Logger['default']) { Logger['default'].trace(); } } }; /** Display a debug notice. Ember build tools will remove any calls to `Ember.debug()` when doing a production build. ```javascript Ember.debug('I\'m a debug notice!'); ``` @method debug @param {String} message A debug message to display. */ Ember['default'].debug = function (message) { Logger['default'].debug("DEBUG: " + message); }; /** Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only). Ember build tools will remove any calls to `Ember.deprecate()` when doing a production build. @method deprecate @param {String} message A description of the deprecation. @param {Boolean|Function} test An optional boolean. If falsy, the deprecation will be displayed. If this is a function, it will be executed and its return value will be used as condition. @param {Object} options An optional object that can be used to pass in a `url` to the transition guide on the emberjs.com website. */ Ember['default'].deprecate = function (message, test, options) { var noDeprecation; if (isPlainFunction(test)) { noDeprecation = test(); } else { noDeprecation = test; } if (noDeprecation) { return; } if (Ember['default'].ENV.RAISE_ON_DEPRECATION) { throw new EmberError['default'](message); } var error; // When using new Error, we can't do the arguments check for Chrome. Alternatives are welcome try { __fail__.fail(); } catch (e) { error = e; } if (arguments.length === 3) { Ember['default'].assert("options argument to Ember.deprecate should be an object", options && typeof options === "object"); if (options.url) { message += " See " + options.url + " for more details."; } } if (Ember['default'].LOG_STACKTRACE_ON_DEPRECATION && error.stack) { var stack; var stackStr = ""; if (error["arguments"]) { // Chrome stack = error.stack.replace(/^\s+at\s+/gm, "").replace(/^([^\(]+?)([\n$])/gm, "{anonymous}($1)$2").replace(/^Object.\s*\(([^\)]+)\)/gm, "{anonymous}($1)").split("\n"); stack.shift(); } else { // Firefox stack = error.stack.replace(/(?:\n@:0)?\s+$/m, "").replace(/^\(/gm, "{anonymous}(").split("\n"); } stackStr = "\n " + stack.slice(2).join("\n "); message = message + stackStr; } Logger['default'].warn("DEPRECATION: " + message); }; /** Alias an old, deprecated method with its new counterpart. Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only) when the assigned method is called. Ember build tools will not remove calls to `Ember.deprecateFunc()`, though no warnings will be shown in production. ```javascript Ember.oldMethod = Ember.deprecateFunc('Please use the new, updated method', Ember.newMethod); ``` @method deprecateFunc @param {String} message A description of the deprecation. @param {Function} func The new function called to replace its deprecated counterpart. @return {Function} a new function that wrapped the original function with a deprecation warning */ Ember['default'].deprecateFunc = function (message, func) { return function () { Ember['default'].deprecate(message); return func.apply(this, arguments); }; }; /** Run a function meant for debugging. Ember build tools will remove any calls to `Ember.runInDebug()` when doing a production build. ```javascript Ember.runInDebug(function() { Ember.Handlebars.EachView.reopen({ didInsertElement: function() { console.log('I\'m happy'); } }); }); ``` @method runInDebug @param {Function} func The function to be executed. @since 1.5.0 */ Ember['default'].runInDebug = function (func) { func(); }; /** Will call `Ember.warn()` if ENABLE_ALL_FEATURES, ENABLE_OPTIONAL_FEATURES, or any specific FEATURES flag is truthy. This method is called automatically in debug canary builds. @private @method _warnIfUsingStrippedFeatureFlags @return {void} */ function _warnIfUsingStrippedFeatureFlags(FEATURES, featuresWereStripped) { if (featuresWereStripped) { Ember['default'].warn("Ember.ENV.ENABLE_ALL_FEATURES is only available in canary builds.", !Ember['default'].ENV.ENABLE_ALL_FEATURES); Ember['default'].warn("Ember.ENV.ENABLE_OPTIONAL_FEATURES is only available in canary builds.", !Ember['default'].ENV.ENABLE_OPTIONAL_FEATURES); for (var key in FEATURES) { if (FEATURES.hasOwnProperty(key) && key !== "isEnabled") { Ember['default'].warn("FEATURE[\"" + key + "\"] is set as enabled, but FEATURE flags are only available in canary builds.", !FEATURES[key]); } } } } if (!Ember['default'].testing) { // Complain if they're using FEATURE flags in builds other than canary Ember['default'].FEATURES["features-stripped-test"] = true; var featuresWereStripped = true; delete Ember['default'].FEATURES["features-stripped-test"]; _warnIfUsingStrippedFeatureFlags(Ember['default'].ENV.FEATURES, featuresWereStripped); // Inform the developer about the Ember Inspector if not installed. var isFirefox = environment['default'].isFirefox; var isChrome = environment['default'].isChrome; if (typeof window !== "undefined" && (isFirefox || isChrome) && window.addEventListener) { window.addEventListener("load", function () { if (document.documentElement && document.documentElement.dataset && !document.documentElement.dataset.emberExtension) { var downloadURL; if (isChrome) { downloadURL = "https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi"; } else if (isFirefox) { downloadURL = "https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/"; } Ember['default'].debug("For more advanced debugging, install the Ember Inspector from " + downloadURL); } }, false); } } /* We are transitioning away from `ember.js` to `ember.debug.js` to make it much clearer that it is only for local development purposes. This flag value is changed by the tooling (by a simple string replacement) so that if `ember.js` (which must be output for backwards compat reasons) is used a nice helpful warning message will be printed out. */ var runningNonEmberDebugJS = true; if (runningNonEmberDebugJS) { Ember['default'].warn("Please use `ember.debug.js` instead of `ember.js` for development and debugging."); } exports.runningNonEmberDebugJS = runningNonEmberDebugJS; }); enifed('ember-extension-support', ['ember-metal/core', 'ember-extension-support/data_adapter', 'ember-extension-support/container_debug_adapter'], function (Ember, DataAdapter, ContainerDebugAdapter) { 'use strict'; /** Ember Extension Support @module ember @submodule ember-extension-support @requires ember-application */ Ember['default'].DataAdapter = DataAdapter['default']; Ember['default'].ContainerDebugAdapter = ContainerDebugAdapter['default']; }); enifed('ember-extension-support/container_debug_adapter', ['exports', 'ember-metal/core', 'ember-runtime/system/native_array', 'ember-runtime/utils', 'ember-runtime/system/string', 'ember-runtime/system/namespace', 'ember-runtime/system/object'], function (exports, Ember, native_array, utils, string, Namespace, EmberObject) { 'use strict'; exports['default'] = EmberObject['default'].extend({ /** The container of the application being debugged. This property will be injected on creation. @property container @default null */ container: null, /** The resolver instance of the application being debugged. This property will be injected on creation. @property resolver @default null */ resolver: null, /** Returns true if it is possible to catalog a list of available classes in the resolver for a given type. @method canCatalogEntriesByType @param {String} type The type. e.g. "model", "controller", "route" @return {boolean} whether a list is available for this type. */ canCatalogEntriesByType: function (type) { if (type === "model" || type === "template") { return false; } return true; }, /** Returns the available classes a given type. @method catalogEntriesByType @param {String} type The type. e.g. "model", "controller", "route" @return {Array} An array of strings. */ catalogEntriesByType: function (type) { var namespaces = native_array.A(Namespace['default'].NAMESPACES); var types = native_array.A(); var typeSuffixRegex = new RegExp("" + string.classify(type) + "$"); namespaces.forEach(function (namespace) { if (namespace !== Ember['default']) { for (var key in namespace) { if (!namespace.hasOwnProperty(key)) { continue; } if (typeSuffixRegex.test(key)) { var klass = namespace[key]; if (utils.typeOf(klass) === "class") { types.push(string.dasherize(key.replace(typeSuffixRegex, ""))); } } } } }); return types; } }); }); enifed('ember-extension-support/data_adapter', ['exports', 'ember-metal/property_get', 'ember-metal/run_loop', 'ember-runtime/system/string', 'ember-runtime/system/namespace', 'ember-runtime/system/object', 'ember-runtime/system/native_array', 'ember-application/system/application'], function (exports, property_get, run, string, Namespace, EmberObject, native_array, Application) { 'use strict'; exports['default'] = EmberObject['default'].extend({ init: function () { this._super.apply(this, arguments); this.releaseMethods = native_array.A(); }, /** The container of the application being debugged. This property will be injected on creation. @property container @default null @since 1.3.0 */ container: null, /** The container-debug-adapter which is used to list all models. @property containerDebugAdapter @default undefined @since 1.5.0 **/ containerDebugAdapter: undefined, /** Number of attributes to send as columns. (Enough to make the record identifiable). @private @property attributeLimit @default 3 @since 1.3.0 */ attributeLimit: 3, /** Stores all methods that clear observers. These methods will be called on destruction. @private @property releaseMethods @since 1.3.0 */ releaseMethods: native_array.A(), /** Specifies how records can be filtered. Records returned will need to have a `filterValues` property with a key for every name in the returned array. @public @method getFilters @return {Array} List of objects defining filters. The object should have a `name` and `desc` property. */ getFilters: function () { return native_array.A(); }, /** Fetch the model types and observe them for changes. @public @method watchModelTypes @param {Function} typesAdded Callback to call to add types. Takes an array of objects containing wrapped types (returned from `wrapModelType`). @param {Function} typesUpdated Callback to call when a type has changed. Takes an array of objects containing wrapped types. @return {Function} Method to call to remove all observers */ watchModelTypes: function (typesAdded, typesUpdated) { var _this = this; var modelTypes = this.getModelTypes(); var releaseMethods = native_array.A(); var typesToSend; typesToSend = modelTypes.map(function (type) { var klass = type.klass; var wrapped = _this.wrapModelType(klass, type.name); releaseMethods.push(_this.observeModelType(klass, typesUpdated)); return wrapped; }); typesAdded(typesToSend); var release = function () { releaseMethods.forEach(function (fn) { return fn(); }); _this.releaseMethods.removeObject(release); }; this.releaseMethods.pushObject(release); return release; }, _nameToClass: function (type) { if (typeof type === "string") { type = this.container.lookupFactory("model:" + type); } return type; }, /** Fetch the records of a given type and observe them for changes. @public @method watchRecords @param {Function} recordsAdded Callback to call to add records. Takes an array of objects containing wrapped records. The object should have the following properties: columnValues: {Object} key and value of a table cell object: {Object} the actual record object @param {Function} recordsUpdated Callback to call when a record has changed. Takes an array of objects containing wrapped records. @param {Function} recordsRemoved Callback to call when a record has removed. Takes the following parameters: index: the array index where the records were removed count: the number of records removed @return {Function} Method to call to remove all observers */ watchRecords: function (type, recordsAdded, recordsUpdated, recordsRemoved) { var _this2 = this; var releaseMethods = native_array.A(); var records = this.getRecords(type); var release; var recordUpdated = function (updatedRecord) { recordsUpdated([updatedRecord]); }; var recordsToSend = records.map(function (record) { releaseMethods.push(_this2.observeRecord(record, recordUpdated)); return _this2.wrapRecord(record); }); var contentDidChange = function (array, idx, removedCount, addedCount) { for (var i = idx; i < idx + addedCount; i++) { var record = array.objectAt(i); var wrapped = _this2.wrapRecord(record); releaseMethods.push(_this2.observeRecord(record, recordUpdated)); recordsAdded([wrapped]); } if (removedCount) { recordsRemoved(idx, removedCount); } }; var observer = { didChange: contentDidChange, willChange: function () { return this; } }; records.addArrayObserver(this, observer); release = function () { releaseMethods.forEach(function (fn) { fn(); }); records.removeArrayObserver(_this2, observer); _this2.releaseMethods.removeObject(release); }; recordsAdded(recordsToSend); this.releaseMethods.pushObject(release); return release; }, /** Clear all observers before destruction @private @method willDestroy */ willDestroy: function () { this._super.apply(this, arguments); this.releaseMethods.forEach(function (fn) { fn(); }); }, /** Detect whether a class is a model. Test that against the model class of your persistence library @private @method detect @param {Class} klass The class to test @return boolean Whether the class is a model class or not */ detect: function (klass) { return false; }, /** Get the columns for a given model type. @private @method columnsForType @param {Class} type The model type @return {Array} An array of columns of the following format: name: {String} name of the column desc: {String} Humanized description (what would show in a table column name) */ columnsForType: function (type) { return native_array.A(); }, /** Adds observers to a model type class. @private @method observeModelType @param {Class} type The model type class @param {Function} typesUpdated Called when a type is modified. @return {Function} The function to call to remove observers */ observeModelType: function (type, typesUpdated) { var _this3 = this; var records = this.getRecords(type); var onChange = function () { typesUpdated([_this3.wrapModelType(type)]); }; var observer = { didChange: function () { run['default'].scheduleOnce("actions", this, onChange); }, willChange: function () { return this; } }; records.addArrayObserver(this, observer); var release = function () { records.removeArrayObserver(_this3, observer); }; return release; }, /** Wraps a given model type and observes changes to it. @private @method wrapModelType @param {Class} type A model class @param {String} Optional name of the class @return {Object} contains the wrapped type and the function to remove observers Format: type: {Object} the wrapped type The wrapped type has the following format: name: {String} name of the type count: {Integer} number of records available columns: {Columns} array of columns to describe the record object: {Class} the actual Model type class release: {Function} The function to remove observers */ wrapModelType: function (type, name) { var records = this.getRecords(type); var typeToSend; typeToSend = { name: name || type.toString(), count: property_get.get(records, "length"), columns: this.columnsForType(type), object: type }; return typeToSend; }, /** Fetches all models defined in the application. @private @method getModelTypes @return {Array} Array of model types */ getModelTypes: function () { var _this4 = this; var containerDebugAdapter = this.get("containerDebugAdapter"); var types; if (containerDebugAdapter.canCatalogEntriesByType("model")) { types = containerDebugAdapter.catalogEntriesByType("model"); } else { types = this._getObjectsOnNamespaces(); } // New adapters return strings instead of classes types = native_array.A(types).map(function (name) { return { klass: _this4._nameToClass(name), name: name }; }); types = native_array.A(types).filter(function (type) { return _this4.detect(type.klass); }); return native_array.A(types); }, /** Loops over all namespaces and all objects attached to them @private @method _getObjectsOnNamespaces @return {Array} Array of model type strings */ _getObjectsOnNamespaces: function () { var _this5 = this; var namespaces = native_array.A(Namespace['default'].NAMESPACES); var types = native_array.A(); namespaces.forEach(function (namespace) { for (var key in namespace) { if (!namespace.hasOwnProperty(key)) { continue; } // Even though we will filter again in `getModelTypes`, // we should not call `lookupContainer` on non-models // (especially when `Ember.MODEL_FACTORY_INJECTIONS` is `true`) if (!_this5.detect(namespace[key])) { continue; } var name = string.dasherize(key); if (!(namespace instanceof Application['default']) && namespace.toString()) { name = "" + namespace + "/" + name; } types.push(name); } }); return types; }, /** Fetches all loaded records for a given type. @private @method getRecords @return {Array} An array of records. This array will be observed for changes, so it should update when new records are added/removed. */ getRecords: function (type) { return native_array.A(); }, /** Wraps a record and observers changes to it. @private @method wrapRecord @param {Object} record The record instance. @return {Object} The wrapped record. Format: columnValues: {Array} searchKeywords: {Array} */ wrapRecord: function (record) { var recordToSend = { object: record }; recordToSend.columnValues = this.getRecordColumnValues(record); recordToSend.searchKeywords = this.getRecordKeywords(record); recordToSend.filterValues = this.getRecordFilterValues(record); recordToSend.color = this.getRecordColor(record); return recordToSend; }, /** Gets the values for each column. @private @method getRecordColumnValues @return {Object} Keys should match column names defined by the model type. */ getRecordColumnValues: function (record) { return {}; }, /** Returns keywords to match when searching records. @private @method getRecordKeywords @return {Array} Relevant keywords for search. */ getRecordKeywords: function (record) { return native_array.A(); }, /** Returns the values of filters defined by `getFilters`. @private @method getRecordFilterValues @param {Object} record The record instance @return {Object} The filter values */ getRecordFilterValues: function (record) { return {}; }, /** Each record can have a color that represents its state. @private @method getRecordColor @param {Object} record The record instance @return {String} The record's color Possible options: black, red, blue, green */ getRecordColor: function (record) { return null; }, /** Observes all relevant properties and re-sends the wrapped record when a change occurs. @private @method observerRecord @param {Object} record The record instance @param {Function} recordUpdated The callback to call when a record is updated. @return {Function} The function to call to remove all observers. */ observeRecord: function (record, recordUpdated) { return function () {}; } }); }); enifed('ember-htmlbars', ['ember-metal/core', 'ember-template-compiler', 'ember-htmlbars/system/make-view-helper', 'ember-htmlbars/system/make_bound_helper', 'ember-htmlbars/helpers', 'ember-htmlbars/helpers/if_unless', 'ember-htmlbars/helpers/with', 'ember-htmlbars/helpers/loc', 'ember-htmlbars/helpers/log', 'ember-htmlbars/helpers/each', 'ember-htmlbars/helpers/-bind-attr-class', 'ember-htmlbars/helpers/-normalize-class', 'ember-htmlbars/helpers/-concat', 'ember-htmlbars/helpers/-join-classes', 'ember-htmlbars/helpers/-legacy-each-with-controller', 'ember-htmlbars/helpers/-legacy-each-with-keyword', 'ember-htmlbars/system/dom-helper', 'ember-htmlbars/system/bootstrap', 'ember-htmlbars/compat'], function (Ember, ember_template_compiler, makeViewHelper, makeBoundHelper, helpers, if_unless, withHelper, locHelper, logHelper, eachHelper, bindAttrClassHelper, normalizeClassHelper, concatHelper, joinClassesHelper, legacyEachWithControllerHelper, legacyEachWithKeywordHelper, DOMHelper) { 'use strict'; helpers.registerHelper("if", if_unless.ifHelper); helpers.registerHelper("unless", if_unless.unlessHelper); helpers.registerHelper("with", withHelper['default']); helpers.registerHelper("loc", locHelper['default']); helpers.registerHelper("log", logHelper['default']); helpers.registerHelper("each", eachHelper['default']); helpers.registerHelper("-bind-attr-class", bindAttrClassHelper['default']); helpers.registerHelper("-normalize-class", normalizeClassHelper['default']); helpers.registerHelper("-concat", concatHelper['default']); helpers.registerHelper("-join-classes", joinClassesHelper['default']); helpers.registerHelper("-legacy-each-with-controller", legacyEachWithControllerHelper['default']); helpers.registerHelper("-legacy-each-with-keyword", legacyEachWithKeywordHelper['default']); Ember['default'].HTMLBars = { _registerHelper: helpers.registerHelper, template: ember_template_compiler.template, compile: ember_template_compiler.compile, precompile: ember_template_compiler.precompile, makeViewHelper: makeViewHelper['default'], makeBoundHelper: makeBoundHelper['default'], registerPlugin: ember_template_compiler.registerPlugin, DOMHelper: DOMHelper['default'] }; }); enifed('ember-htmlbars/compat', ['exports', 'ember-metal/core', 'ember-htmlbars/helpers', 'ember-htmlbars/compat/helper', 'ember-htmlbars/compat/handlebars-get', 'ember-htmlbars/compat/make-bound-helper', 'ember-htmlbars/compat/register-bound-helper', 'ember-htmlbars/system/make-view-helper', 'ember-htmlbars/utils/string'], function (exports, Ember, helpers, helper, compatHandlebarsGet, compatMakeBoundHelper, compatRegisterBoundHelper, makeViewHelper, string) { 'use strict'; var EmberHandlebars = Ember['default'].Handlebars = Ember['default'].Handlebars || {}; EmberHandlebars.helpers = helpers['default']; EmberHandlebars.helper = helper.handlebarsHelper; EmberHandlebars.registerHelper = helper.registerHandlebarsCompatibleHelper; EmberHandlebars.registerBoundHelper = compatRegisterBoundHelper['default']; EmberHandlebars.makeBoundHelper = compatMakeBoundHelper['default']; EmberHandlebars.get = compatHandlebarsGet['default']; EmberHandlebars.makeViewHelper = makeViewHelper['default']; EmberHandlebars.SafeString = string.SafeString; EmberHandlebars.Utils = { escapeExpression: string.escapeExpression }; exports['default'] = EmberHandlebars; }); enifed('ember-htmlbars/compat/handlebars-get', ['exports'], function (exports) { 'use strict'; exports['default'] = handlebarsGet; /** @module ember @submodule ember-htmlbars */ /** Lookup both on root and on window. If the path starts with a keyword, the corresponding object will be looked up in the template's data hash and used to resolve the path. @method get @for Ember.Handlebars @param {Object} root The object to look up the property on @param {String} path The path to be lookedup @param {Object} options The template's option hash @deprecated */ function handlebarsGet(root, path, options) { Ember.deprecate('Usage of Ember.Handlebars.get is deprecated, use a Component or Ember.Handlebars.makeBoundHelper instead.'); return options.legacyGetPath(path); } }); enifed('ember-htmlbars/compat/helper', ['exports', 'ember-htmlbars/helpers', 'ember-views/views/view', 'ember-views/views/component', 'ember-htmlbars/system/make-view-helper', 'ember-htmlbars/compat/make-bound-helper', 'ember-metal/streams/utils', 'ember-htmlbars/keywords'], function (exports, helpers, View, Component, makeViewHelper, makeBoundHelper, utils, keywords) { 'use strict'; exports.registerHandlebarsCompatibleHelper = registerHandlebarsCompatibleHelper; exports.handlebarsHelper = handlebarsHelper; var slice = [].slice; function calculateCompatType(item) { if (utils.isStream(item)) { return "ID"; } else { var itemType = typeof item; return itemType.toUpperCase(); } } function pathFor(param) { if (utils.isStream(param)) { // param arguments to helpers may have their path prefixes with self. For // example {{box-thing foo}} may have a param path of `self.foo` depending // on scope. if (param.source && param.source.dependee && param.source.dependee.label === "self") { return param.path.slice(5); } else { return param.path; } } else { return param; } } /** Wraps an Handlebars helper with an HTMLBars helper for backwards compatibility. @class HandlebarsCompatibleHelper @constructor @private */ function HandlebarsCompatibleHelper(fn) { this.helperFunction = function helperFunc(params, hash, options, env, scope) { var param, fnResult; var hasBlock = options.template && options.template.yield; var handlebarsOptions = { hash: {}, types: new Array(params.length), hashTypes: {} }; handlebarsOptions.hash = {}; if (hasBlock) { handlebarsOptions.fn = function () { options.template.yield(); }; if (options.inverse.yield) { handlebarsOptions.inverse = function () { options.inverse.yield(); }; } } for (var prop in hash) { param = hash[prop]; handlebarsOptions.hashTypes[prop] = calculateCompatType(param); handlebarsOptions.hash[prop] = pathFor(param); } var args = new Array(params.length); for (var i = 0, l = params.length; i < l; i++) { param = params[i]; handlebarsOptions.types[i] = calculateCompatType(param); args[i] = pathFor(param); } handlebarsOptions.legacyGetPath = function (path) { return env.hooks.get(env, scope, path).value(); }; handlebarsOptions.data = { view: scope.view }; args.push(handlebarsOptions); fnResult = fn.apply(this, args); if (options.element) { Ember.deprecate("Returning a string of attributes from a helper inside an element is deprecated."); applyAttributes(env.dom, options.element, fnResult); } else if (!options.template.yield) { return fnResult; } }; this.isHTMLBars = true; } HandlebarsCompatibleHelper.prototype = { preprocessArguments: function () {} }; function registerHandlebarsCompatibleHelper(name, value) { if (value && value.isLegacyViewHelper) { keywords.registerKeyword(name, function (morph, env, scope, params, hash, template, inverse, visitor) { Ember.assert("You can only pass attributes (such as name=value) not bare " + "values to a helper for a View found in '" + value.viewClass + "'", params.length === 0); env.hooks.keyword("view", morph, env, scope, [value.viewClass], hash, template, inverse, visitor); return true; }); return; } var helper; if (value && value.isHTMLBars) { helper = value; } else { helper = new HandlebarsCompatibleHelper(value); } helpers['default'][name] = helper; } function handlebarsHelper(name, value) { Ember.assert("You tried to register a component named '" + name + "', but component names must include a '-'", !Component['default'].detect(value) || name.match(/-/)); if (View['default'].detect(value)) { helpers['default'][name] = makeViewHelper['default'](value); } else { var boundHelperArgs = slice.call(arguments, 1); var boundFn = makeBoundHelper['default'].apply(this, boundHelperArgs); helpers['default'][name] = boundFn; } } function applyAttributes(dom, element, innerString) { var string = "<" + element.tagName + " " + innerString + ">"; var fragment = dom.parseHTML(string, dom.createElement(element.tagName)); var attrs = fragment.firstChild.attributes; for (var i = 0, l = attrs.length; i < l; i++) { element.setAttributeNode(attrs[i].cloneNode()); } } exports['default'] = HandlebarsCompatibleHelper; }); enifed('ember-htmlbars/compat/make-bound-helper', ['exports', 'ember-metal/streams/utils'], function (exports, utils) { 'use strict'; exports['default'] = makeBoundHelper; function makeBoundHelper(fn) { for (var _len = arguments.length, dependentKeys = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { dependentKeys[_key - 1] = arguments[_key]; } return { _dependentKeys: dependentKeys, isHandlebarsCompat: true, isHTMLBars: true, helperFunction: function (params, hash, templates) { Ember.assert("registerBoundHelper-generated helpers do not support use with Handlebars blocks.", !templates.template.yield); var args = utils.readArray(params); var properties = new Array(params.length); for (var i = 0, l = params.length; i < l; i++) { var param = params[i]; if (utils.isStream(param)) { properties[i] = param.label; } else { properties[i] = param; } } args.push({ hash: utils.readHash(hash), templates: templates, data: { properties: properties } }); return fn.apply(undefined, args); } }; } }); enifed('ember-htmlbars/compat/register-bound-helper', ['exports', 'ember-htmlbars/helpers', 'ember-htmlbars/compat/make-bound-helper'], function (exports, helpers, makeBoundHelper) { 'use strict'; exports['default'] = registerBoundHelper; /** @module ember @submodule ember-htmlbars */ var slice = [].slice; /** Register a bound handlebars helper. Bound helpers behave similarly to regular handlebars helpers, with the added ability to re-render when the underlying data changes. ## Simple example ```javascript Ember.Handlebars.registerBoundHelper('capitalize', function(value) { return Ember.String.capitalize(value); }); ``` The above bound helper can be used inside of templates as follows: ```handlebars {{capitalize name}} ``` In this case, when the `name` property of the template's context changes, the rendered value of the helper will update to reflect this change. ## Example with options Like normal handlebars helpers, bound helpers have access to the options passed into the helper call. ```javascript Ember.Handlebars.registerBoundHelper('repeat', function(value, options) { var count = options.hash.count; var a = []; while(a.length < count) { a.push(value); } return a.join(''); }); ``` This helper could be used in a template as follows: ```handlebars {{repeat text count=3}} ``` ## Example with bound options Bound hash options are also supported. Example: ```handlebars {{repeat text count=numRepeats}} ``` In this example, count will be bound to the value of the `numRepeats` property on the context. If that property changes, the helper will be re-rendered. ## Example with extra dependencies The `Ember.Handlebars.registerBoundHelper` method takes a variable length third parameter which indicates extra dependencies on the passed in value. This allows the handlebars helper to update when these dependencies change. ```javascript Ember.Handlebars.registerBoundHelper('capitalizeName', function(value) { return value.get('name').toUpperCase(); }, 'name'); ``` ## Example with multiple bound properties `Ember.Handlebars.registerBoundHelper` supports binding to multiple properties, e.g.: ```javascript Ember.Handlebars.registerBoundHelper('concatenate', function() { var values = Array.prototype.slice.call(arguments, 0, -1); return values.join('||'); }); ``` Which allows for template syntax such as `{{concatenate prop1 prop2}}` or `{{concatenate prop1 prop2 prop3}}`. If any of the properties change, the helper will re-render. Note that dependency keys cannot be using in conjunction with multi-property helpers, since it is ambiguous which property the dependent keys would belong to. ## Use with unbound helper The `{{unbound}}` helper can be used with bound helper invocations to render them in their unbound form, e.g. ```handlebars {{unbound capitalize name}} ``` In this example, if the name property changes, the helper will not re-render. ## Use with blocks not supported Bound helpers do not support use with Handlebars blocks or the addition of child views of any kind. @method registerBoundHelper @for Ember.Handlebars @param {String} name @param {Function} function @param {String} dependentKeys* */ function registerBoundHelper(name, fn) { var boundHelperArgs = slice.call(arguments, 1); var boundFn = makeBoundHelper['default'].apply(this, boundHelperArgs); helpers['default'][name] = boundFn; } }); enifed('ember-htmlbars/env', ['exports', 'ember-metal/environment', 'htmlbars-runtime', 'ember-metal/merge', 'ember-htmlbars/hooks/subexpr', 'ember-htmlbars/hooks/concat', 'ember-htmlbars/hooks/link-render-node', 'ember-htmlbars/hooks/create-fresh-scope', 'ember-htmlbars/hooks/bind-shadow-scope', 'ember-htmlbars/hooks/bind-self', 'ember-htmlbars/hooks/bind-scope', 'ember-htmlbars/hooks/bind-local', 'ember-htmlbars/hooks/update-self', 'ember-htmlbars/hooks/get-root', 'ember-htmlbars/hooks/get-child', 'ember-htmlbars/hooks/get-value', 'ember-htmlbars/hooks/get-cell-or-value', 'ember-htmlbars/hooks/cleanup-render-node', 'ember-htmlbars/hooks/destroy-render-node', 'ember-htmlbars/hooks/did-render-node', 'ember-htmlbars/hooks/will-cleanup-tree', 'ember-htmlbars/hooks/did-cleanup-tree', 'ember-htmlbars/hooks/classify', 'ember-htmlbars/hooks/component', 'ember-htmlbars/hooks/lookup-helper', 'ember-htmlbars/hooks/has-helper', 'ember-htmlbars/hooks/invoke-helper', 'ember-htmlbars/hooks/element', 'ember-htmlbars/helpers', 'ember-htmlbars/keywords', 'ember-htmlbars/system/dom-helper', 'ember-htmlbars/keywords/debugger', 'ember-htmlbars/keywords/with', 'ember-htmlbars/keywords/outlet', 'ember-htmlbars/keywords/real_outlet', 'ember-htmlbars/keywords/customized_outlet', 'ember-htmlbars/keywords/unbound', 'ember-htmlbars/keywords/view', 'ember-htmlbars/keywords/component', 'ember-htmlbars/keywords/partial', 'ember-htmlbars/keywords/input', 'ember-htmlbars/keywords/textarea', 'ember-htmlbars/keywords/collection', 'ember-htmlbars/keywords/template', 'ember-htmlbars/keywords/legacy-yield', 'ember-htmlbars/keywords/mut', 'ember-htmlbars/keywords/each', 'ember-htmlbars/keywords/readonly'], function (exports, environment, htmlbars_runtime, merge, subexpr, concat, linkRenderNode, createFreshScope, bindShadowScope, bindSelf, bindScope, bindLocal, updateSelf, getRoot, getChild, getValue, getCellOrValue, cleanupRenderNode, destroyRenderNode, didRenderNode, willCleanupTree, didCleanupTree, classify, component, lookupHelper, hasHelper, invokeHelper, element, helpers, keywords, DOMHelper, debuggerKeyword, withKeyword, outlet, realOutlet, customizedOutlet, unbound, view, componentKeyword, partial, input, textarea, collection, templateKeyword, legacyYield, mut, each, readonly) { 'use strict'; var emberHooks = merge['default']({}, htmlbars_runtime.hooks); emberHooks.keywords = keywords['default']; merge['default'](emberHooks, { linkRenderNode: linkRenderNode['default'], createFreshScope: createFreshScope['default'], bindShadowScope: bindShadowScope['default'], bindSelf: bindSelf['default'], bindScope: bindScope['default'], bindLocal: bindLocal['default'], updateSelf: updateSelf['default'], getRoot: getRoot['default'], getChild: getChild['default'], getValue: getValue['default'], getCellOrValue: getCellOrValue['default'], subexpr: subexpr['default'], concat: concat['default'], cleanupRenderNode: cleanupRenderNode['default'], destroyRenderNode: destroyRenderNode['default'], willCleanupTree: willCleanupTree['default'], didCleanupTree: didCleanupTree['default'], didRenderNode: didRenderNode['default'], classify: classify['default'], component: component['default'], lookupHelper: lookupHelper['default'], hasHelper: hasHelper['default'], invokeHelper: invokeHelper['default'], element: element['default'] });keywords.registerKeyword("debugger", debuggerKeyword['default']); keywords.registerKeyword("with", withKeyword['default']); keywords.registerKeyword("outlet", outlet['default']); keywords.registerKeyword("@real_outlet", realOutlet['default']); keywords.registerKeyword("@customized_outlet", customizedOutlet['default']); keywords.registerKeyword("unbound", unbound['default']); keywords.registerKeyword("view", view['default']); keywords.registerKeyword("component", componentKeyword['default']); keywords.registerKeyword("partial", partial['default']); keywords.registerKeyword("template", templateKeyword['default']); keywords.registerKeyword("input", input['default']); keywords.registerKeyword("textarea", textarea['default']); keywords.registerKeyword("collection", collection['default']); keywords.registerKeyword("legacy-yield", legacyYield['default']); keywords.registerKeyword("mut", mut['default']); keywords.registerKeyword("@mut", mut.privateMut); keywords.registerKeyword("each", each['default']); keywords.registerKeyword("readonly", readonly['default']); exports['default'] = { hooks: emberHooks, helpers: helpers['default'], useFragmentCache: true }; var domHelper = environment['default'].hasDOM ? new DOMHelper['default']() : null; exports.domHelper = domHelper; }); enifed('ember-htmlbars/helpers', ['exports', 'ember-metal/platform/create'], function (exports, o_create) { 'use strict'; exports.registerHelper = registerHelper; var helpers = o_create['default'](null); /** @module ember @submodule ember-htmlbars */ /** @private @method _registerHelper @for Ember.HTMLBars @param {String} name @param {Object|Function} helperFunc the helper function to add */ function registerHelper(name, helperFunc) { helpers[name] = helperFunc; } exports['default'] = helpers; }); enifed('ember-htmlbars/helpers/-bind-attr-class', ['exports', 'ember-metal/property_get', 'ember-metal/utils'], function (exports, property_get, utils) { 'use strict'; exports['default'] = bindAttrClassHelper; /** @module ember @submodule ember-htmlbars */ function bindAttrClassHelper(params) { var value = params[0]; if (utils.isArray(value)) { value = property_get.get(value, 'length') !== 0; } if (value === true) { return params[1]; }if (value === false || value === undefined || value === null) { return ''; } else { return value; } } }); enifed('ember-htmlbars/helpers/-concat', ['exports'], function (exports) { 'use strict'; exports['default'] = concat; /** @private This private helper is used by the legacy class bindings AST transformer to concatenate class names together. */ function concat(params, hash) { return params.join(hash.separator); } }); enifed('ember-htmlbars/helpers/-join-classes', ['exports'], function (exports) { 'use strict'; exports['default'] = joinClasses; /** @private this private helper is used to join and compact a list of class names */ function joinClasses(classNames) { var result = []; for (var i = 0, l = classNames.length; i < l; i++) { var className = classNames[i]; if (className) { result.push(className); } } return result.join(' '); } }); enifed('ember-htmlbars/helpers/-legacy-each-with-controller', ['exports', 'ember-metal/property_get', 'ember-metal/enumerable_utils', 'ember-htmlbars/utils/normalize-self'], function (exports, property_get, enumerable_utils, normalizeSelf) { 'use strict'; exports['default'] = legacyEachWithControllerHelper; function legacyEachWithControllerHelper(params, hash, blocks) { var list = params[0]; var keyPath = hash.key; // TODO: Correct falsy semantics if (!list || property_get.get(list, "length") === 0) { if (blocks.inverse.yield) { blocks.inverse.yield(); } return; } enumerable_utils.forEach(list, function (item, i) { var self; if (blocks.template.arity === 0) { Ember.deprecate(deprecation); self = normalizeSelf['default'](item); self = bindController(self, true); } var key = keyPath ? property_get.get(item, keyPath) : String(i); blocks.template.yieldItem(key, [item, i], self); }); } function bindController(controller, isSelf) { return { controller: controller, hasBoundController: true, self: controller ? controller : undefined }; } var deprecation = "Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each items as |item|}}`) instead."; exports.deprecation = deprecation; }); enifed('ember-htmlbars/helpers/-legacy-each-with-keyword', ['exports', 'ember-metal/property_get', 'ember-metal/enumerable_utils', 'ember-views/streams/should_display'], function (exports, property_get, enumerable_utils, shouldDisplay) { 'use strict'; exports['default'] = legacyEachWithKeywordHelper; function legacyEachWithKeywordHelper(params, hash, blocks) { var list = params[0]; var keyPath = hash.key; var legacyKeyword = hash["-legacy-keyword"]; if (shouldDisplay['default'](list)) { enumerable_utils.forEach(list, function (item, i) { var self; if (legacyKeyword) { self = bindKeyword(self, legacyKeyword, item); } var key = keyPath ? property_get.get(item, keyPath) : String(i); blocks.template.yieldItem(key, [item, i], self); }); } else if (blocks.inverse.yield) { blocks.inverse.yield(); } } function bindKeyword(self, keyword, item) { var _ref; return (_ref = {}, _ref.self = self, _ref[keyword] = item, _ref); } var deprecation = "Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each items as |item|}}`) instead."; exports.deprecation = deprecation; }); enifed('ember-htmlbars/helpers/-normalize-class', ['exports', 'ember-runtime/system/string', 'ember-metal/path_cache'], function (exports, string, path_cache) { 'use strict'; exports['default'] = normalizeClass; function normalizeClass(params, hash) { var propName = params[0]; var value = params[1]; var activeClass = hash.activeClass; var inactiveClass = hash.inactiveClass; // When using the colon syntax, evaluate the truthiness or falsiness // of the value to determine which className to return if (activeClass || inactiveClass) { if (!!value) { return activeClass; } else { return inactiveClass; } // If value is a Boolean and true, return the dasherized property // name. } else if (value === true) { // Only apply to last segment in the path if (propName && path_cache.isPath(propName)) { var segments = propName.split("."); propName = segments[segments.length - 1]; } return string.dasherize(propName); // If the value is not false, undefined, or null, return the current // value of the property. } else if (value !== false && value != null) { return value; // Nothing to display. Return null so that the old class is removed // but no new class is added. } else { return null; } } }); enifed('ember-htmlbars/helpers/bind-attr', function () { 'use strict'; /** @module ember @submodule ember-htmlbars */ /** `bind-attr` allows you to create a binding between DOM element attributes and Ember objects. For example: ```handlebars imageTitle}} ``` The above handlebars template will fill the ``'s `src` attribute with the value of the property referenced with `imageUrl` and its `alt` attribute with the value of the property referenced with `imageTitle`. If the rendering context of this template is the following object: ```javascript { imageUrl: 'http://lolcats.info/haz-a-funny', imageTitle: 'A humorous image of a cat' } ``` The resulting HTML output will be: ```html A humorous image of a cat ``` `bind-attr` cannot redeclare existing DOM element attributes. The use of `src` in the following `bind-attr` example will be ignored and the hard coded value of `src="/failwhale.gif"` will take precedence: ```handlebars imageTitle}} ``` ### `bind-attr` and the `class` attribute `bind-attr` supports a special syntax for handling a number of cases unique to the `class` DOM element attribute. The `class` attribute combines multiple discrete values into a single attribute as a space-delimited list of strings. Each string can be: * a string return value of an object's property. * a boolean return value of an object's property * a hard-coded value A string return value works identically to other uses of `bind-attr`. The return value of the property will become the value of the attribute. For example, the following view and template: ```javascript AView = View.extend({ someProperty: function() { return "aValue"; }.property() }) ``` ```handlebars ``` Result in the following rendered output: ```html ``` A boolean return value will insert a specified class name if the property returns `true` and remove the class name if the property returns `false`. A class name is provided via the syntax `somePropertyName:class-name-if-true`. ```javascript AView = View.extend({ someBool: true }) ``` ```handlebars ``` Result in the following rendered output: ```html ``` An additional section of the binding can be provided if you want to replace the existing class instead of removing it when the boolean value changes: ```handlebars ``` A hard-coded value can be used by prepending `:` to the desired class name: `:class-name-to-always-apply`. ```handlebars ``` Results in the following rendered output: ```html ``` All three strategies - string return value, boolean return value, and hard-coded value – can be combined in a single declaration: ```handlebars ``` @method bind-attr @for Ember.Handlebars.helpers @deprecated @param {Hash} options @return {String} HTML string */ /** See `bind-attr` @method bindAttr @for Ember.Handlebars.helpers @deprecated @param {Function} context @param {Hash} options @return {String} HTML string */ }); enifed('ember-htmlbars/helpers/each', ['exports', 'ember-metal/property_get', 'ember-metal/enumerable_utils', 'ember-htmlbars/utils/normalize-self', 'ember-views/streams/should_display'], function (exports, property_get, enumerable_utils, normalizeSelf, shouldDisplay) { 'use strict'; exports['default'] = eachHelper; function eachHelper(params, hash, blocks) { var list = params[0]; var keyPath = hash.key; if (shouldDisplay['default'](list)) { enumerable_utils.forEach(list, function (item, i) { var self; if (blocks.template.arity === 0) { Ember.deprecate(deprecation); self = normalizeSelf['default'](item); } var key = keyPath ? property_get.get(item, keyPath) : String(i); blocks.template.yieldItem(key, [item, i], self); }); } else if (blocks.inverse.yield) { blocks.inverse.yield(); } } var deprecation = "Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each items as |item|}}`) instead."; exports.deprecation = deprecation; }); enifed('ember-htmlbars/helpers/if_unless', ['exports', 'ember-metal/core', 'ember-views/streams/should_display'], function (exports, Ember, shouldDisplay) { 'use strict'; exports.ifHelper = ifHelper; exports.unlessHelper = unlessHelper; /** @module ember @submodule ember-htmlbars */ function ifHelper(params, hash, options) { return ifUnless(params, hash, options, shouldDisplay['default'](params[0])); } /** The `unless` helper is the inverse of the `if` helper. Its block will be rendered if the expression contains a falsey value. All forms of the `if` helper can also be used with `unless`. @method unless @for Ember.Handlebars.helpers */ function unlessHelper(params, hash, options) { return ifUnless(params, hash, options, !shouldDisplay['default'](params[0])); } function ifUnless(params, hash, options, truthy) { Ember['default'].assert("The block form of the `if` and `unless` helpers expect exactly one " + "argument, e.g. `{{#if newMessages}} You have new messages. {{/if}}.`", !options.template.yield || params.length === 1); Ember['default'].assert("The inline form of the `if` and `unless` helpers expect two or " + "three arguments, e.g. `{{if trialExpired 'Expired' expiryDate}}` " + "or `{{unless isFirstLogin 'Welcome back!'}}`.", !!options.template.yield || params.length === 2 || params.length === 3); if (truthy) { if (options.template.yield) { options.template.yield(); } else { return params[1]; } } else { if (options.inverse.yield) { options.inverse.yield(); } else { return params[2]; } } } }); enifed('ember-htmlbars/helpers/loc', ['exports', 'ember-runtime/system/string'], function (exports, string) { 'use strict'; exports['default'] = locHelper; function locHelper(params) { return string.loc.apply(null, params); } }); enifed('ember-htmlbars/helpers/log', ['exports', 'ember-metal/logger'], function (exports, Logger) { 'use strict'; exports['default'] = logHelper; /** @module ember @submodule ember-htmlbars */ function logHelper(values) { Logger['default'].log.apply(null, values); } }); enifed('ember-htmlbars/helpers/with', ['exports', 'ember-htmlbars/utils/normalize-self', 'ember-views/streams/should_display'], function (exports, normalizeSelf, shouldDisplay) { 'use strict'; exports['default'] = withHelper; /** @module ember @submodule ember-htmlbars */ function withHelper(params, hash, options) { if (shouldDisplay['default'](params[0])) { var preserveContext = false; if (options.template.arity !== 0) { preserveContext = true; } if (preserveContext) { this.yield([params[0]]); } else { var _self = normalizeSelf['default'](params[0]); if (hash.controller) { _self = { hasBoundController: true, controller: hash.controller, self: _self }; } this.yield([], _self); } } else if (options.inverse && options.inverse.yield) { options.inverse.yield([]); } } }); enifed('ember-htmlbars/hooks/bind-local', ['exports', 'ember-metal/streams/stream', 'ember-metal/streams/proxy-stream'], function (exports, Stream, ProxyStream) { 'use strict'; exports['default'] = bindLocal; /** @module ember @submodule ember-htmlbars */ function bindLocal(env, scope, key, value) { var isExisting = scope.locals.hasOwnProperty(key); if (isExisting) { var existing = scope.locals[key]; if (existing !== value) { existing.setSource(value); } existing.notify(); } else { var newValue = Stream['default'].wrap(value, ProxyStream['default'], key); scope.locals[key] = newValue; } } }); enifed('ember-htmlbars/hooks/bind-scope', ['exports'], function (exports) { 'use strict'; exports['default'] = bindScope; function bindScope(env, scope) {} }); enifed('ember-htmlbars/hooks/bind-self', ['exports', 'ember-metal/streams/proxy-stream', 'ember-htmlbars/utils/subscribe'], function (exports, ProxyStream, subscribe) { 'use strict'; exports['default'] = bindSelf; /** @module ember @submodule ember-htmlbars */ function bindSelf(env, scope, _self) { var self = _self; if (self && self.hasBoundController) { var controller = self.controller; self = self.self; newStream(scope.locals, "controller", controller || self); } if (self && self.isView) { scope.view = self; newStream(scope.locals, "view", self, null); newStream(scope.locals, "controller", scope.locals.view.getKey("controller")); newStream(scope, "self", scope.locals.view.getKey("context"), null, true); return; } newStream(scope, "self", self, null, true); if (!scope.locals.controller) { scope.locals.controller = scope.self; } } function newStream(scope, key, newValue, renderNode, isSelf) { var stream = new ProxyStream['default'](newValue, isSelf ? "" : key); if (renderNode) { subscribe['default'](renderNode, scope, stream); } scope[key] = stream; } }); enifed('ember-htmlbars/hooks/bind-shadow-scope', ['exports', 'ember-views/views/component', 'ember-metal/streams/proxy-stream', 'ember-htmlbars/utils/subscribe'], function (exports, Component, ProxyStream, subscribe) { 'use strict'; exports['default'] = bindShadowScope; /** @module ember @submodule ember-htmlbars */ function bindShadowScope(env, parentScope, shadowScope, options) { if (!options) { return; } var didOverrideController = false; if (parentScope && parentScope.overrideController) { didOverrideController = true; shadowScope.locals.controller = parentScope.locals.controller; } var view = options.view; if (view && !(view instanceof Component['default'])) { newStream(shadowScope.locals, 'view', view, null); if (!didOverrideController) { newStream(shadowScope.locals, 'controller', shadowScope.locals.view.getKey('controller')); } if (view.isView) { newStream(shadowScope, 'self', shadowScope.locals.view.getKey('context'), null, true); } } shadowScope.view = view; if (view && options.attrs) { shadowScope.component = view; } if ('attrs' in options) { shadowScope.attrs = options.attrs; } return shadowScope; } function newStream(scope, key, newValue, renderNode, isSelf) { var stream = new ProxyStream['default'](newValue, isSelf ? '' : key); if (renderNode) { subscribe['default'](renderNode, scope, stream); } scope[key] = stream; } }); enifed('ember-htmlbars/hooks/classify', ['exports', 'ember-htmlbars/utils/is-component'], function (exports, isComponent) { 'use strict'; exports['default'] = classify; /** @module ember @submodule ember-htmlbars */ function classify(env, scope, path) { if (isComponent['default'](env, scope, path)) { return "component"; } return null; } }); enifed('ember-htmlbars/hooks/cleanup-render-node', ['exports'], function (exports) { 'use strict'; exports['default'] = cleanupRenderNode; /** @module ember @submodule ember-htmlbars */ function cleanupRenderNode(renderNode) { if (renderNode.cleanup) { renderNode.cleanup(); } } }); enifed('ember-htmlbars/hooks/component', ['exports', 'ember-htmlbars/node-managers/component-node-manager'], function (exports, ComponentNodeManager) { 'use strict'; exports['default'] = componentHook; function componentHook(renderNode, env, scope, _tagName, params, attrs, templates, visitor) { var state = renderNode.state; // Determine if this is an initial render or a re-render if (state.manager) { state.manager.rerender(env, attrs, visitor); return; } var tagName = _tagName; var isAngleBracket = false; if (tagName.charAt(0) === "<") { tagName = tagName.slice(1, -1); isAngleBracket = true; } var read = env.hooks.getValue; var parentView = read(scope.view); var manager = ComponentNodeManager['default'].create(renderNode, env, { tagName: tagName, params: params, attrs: attrs, parentView: parentView, templates: templates, isAngleBracket: isAngleBracket, parentScope: scope }); state.manager = manager; manager.render(env, visitor); } }); enifed('ember-htmlbars/hooks/concat', ['exports', 'ember-metal/streams/utils'], function (exports, utils) { 'use strict'; exports['default'] = concat; /** @module ember @submodule ember-htmlbars */ function concat(env, parts) { return utils.concat(parts, ""); } }); enifed('ember-htmlbars/hooks/create-fresh-scope', ['exports'], function (exports) { 'use strict'; exports['default'] = createFreshScope; function createFreshScope() { return { self: null, blocks: {}, component: null, view: null, attrs: null, locals: {}, localPresent: {} }; } }); enifed('ember-htmlbars/hooks/destroy-render-node', ['exports'], function (exports) { 'use strict'; exports['default'] = destroyRenderNode; /** @module ember @submodule ember-htmlbars */ function destroyRenderNode(renderNode) { if (renderNode.emberView) { renderNode.emberView.destroy(); } var streamUnsubscribers = renderNode.streamUnsubscribers; if (streamUnsubscribers) { for (var i = 0, l = streamUnsubscribers.length; i < l; i++) { streamUnsubscribers[i](); } } } }); enifed('ember-htmlbars/hooks/did-cleanup-tree', ['exports'], function (exports) { 'use strict'; exports['default'] = didCleanupTree; function didCleanupTree(env) { var view; if (view = env.view) { view.ownerView.isDestroyingSubtree = false; } } }); enifed('ember-htmlbars/hooks/did-render-node', ['exports'], function (exports) { 'use strict'; exports['default'] = didRenderNode; function didRenderNode(morph, env) { env.renderedNodes[morph.guid] = true; } }); enifed('ember-htmlbars/hooks/element', ['exports', 'ember-htmlbars/system/lookup-helper', 'htmlbars-runtime/hooks'], function (exports, lookup_helper, hooks) { 'use strict'; exports['default'] = emberElement; /** @module ember @submodule ember-htmlbars */ var fakeElement; function updateElementAttributesFromString(element, string) { if (!fakeElement) { fakeElement = document.createElement("div"); } fakeElement.innerHTML = "<" + element.tagName + " " + string + "><" + "/" + element.tagName + ">"; var attrs = fakeElement.firstChild.attributes; for (var i = 0, l = attrs.length; i < l; i++) { var attr = attrs[i]; if (attr.specified) { element.setAttribute(attr.name, attr.value); } } } function emberElement(morph, env, scope, path, params, hash, visitor) { if (hooks.handleRedirect(morph, env, scope, path, params, hash, null, null, visitor)) { return; } var result; var helper = lookup_helper.findHelper(path, scope.self, env); if (helper) { result = env.hooks.invokeHelper(null, env, scope, null, params, hash, helper, { element: morph.element }).value; } else { result = env.hooks.get(env, scope, path); } var value = env.hooks.getValue(result); if (value) { Ember.deprecate("Returning a string of attributes from a helper inside an element is deprecated."); updateElementAttributesFromString(morph.element, value); } } }); enifed('ember-htmlbars/hooks/get-cell-or-value', ['exports', 'ember-metal/streams/utils', 'ember-htmlbars/keywords/mut'], function (exports, utils, mut) { 'use strict'; exports['default'] = getCellOrValue; function getCellOrValue(ref) { if (ref && ref[mut.MUTABLE_REFERENCE]) { // reify the mutable reference into a mutable cell return ref.cell(); } // get the value out of the reference return utils.read(ref); } }); enifed('ember-htmlbars/hooks/get-child', ['exports', 'ember-metal/streams/utils'], function (exports, utils) { 'use strict'; exports['default'] = getChild; /** @module ember @submodule ember-htmlbars */ function getChild(parent, key) { if (utils.isStream(parent)) { return parent.getKey(key); } // This should only happen when we are looking at an `attrs` hash // That might change if it is possible to pass object literals // through the templating system. return parent[key]; } }); enifed('ember-htmlbars/hooks/get-root', ['exports', 'ember-metal/core', 'ember-metal/path_cache', 'ember-metal/streams/proxy-stream'], function (exports, Ember, path_cache, ProxyStream) { 'use strict'; exports['default'] = getRoot; /** @module ember @submodule ember-htmlbars */ function getRoot(scope, key) { if (key === "this") { return [scope.self]; } else if (key === "hasBlock") { return [!!scope.blocks["default"]]; } else if (key === "hasBlockParams") { return [!!(scope.blocks["default"] && scope.blocks["default"].arity)]; } else if (path_cache.isGlobal(key) && Ember['default'].lookup[key]) { return [getGlobal(key)]; } else if (key in scope.locals) { return [scope.locals[key]]; } else { return [getKey(scope, key)]; } } function getKey(scope, key) { if (key === "attrs" && scope.attrs) { return scope.attrs; } var self = scope.self || scope.locals.view; if (scope.attrs && key in scope.attrs) { // TODO: attrs // Ember.deprecate("You accessed the `" + key + "` attribute directly. Please use `attrs." + key + "` instead."); return scope.attrs[key]; } else if (self) { return self.getKey(key); } } function getGlobal(name) { Ember['default'].deprecate("Global lookup of " + name + " from a Handlebars template is deprecated."); // This stream should be memoized, but this path is deprecated and // will be removed soon so it's not worth the trouble. return new ProxyStream['default'](Ember['default'].lookup[name], name); } }); enifed('ember-htmlbars/hooks/get-value', ['exports', 'ember-metal/streams/utils', 'ember-views/compat/attrs-proxy'], function (exports, utils, attrs_proxy) { 'use strict'; exports['default'] = getValue; /** @module ember @submodule ember-htmlbars */ function getValue(ref) { var value = utils.read(ref); if (value && value[attrs_proxy.MUTABLE_CELL]) { return value.value; } return value; } }); enifed('ember-htmlbars/hooks/has-helper', ['exports', 'ember-htmlbars/system/lookup-helper'], function (exports, lookup_helper) { 'use strict'; exports['default'] = hasHelperHook; function hasHelperHook(env, scope, helperName) { return !!lookup_helper.findHelper(helperName, scope.self, env); } }); enifed('ember-htmlbars/hooks/invoke-helper', ['exports', 'ember-metal/core', 'ember-htmlbars/hooks/get-value'], function (exports, Ember, getValue) { 'use strict'; exports['default'] = invokeHelper; function invokeHelper(morph, env, scope, visitor, _params, _hash, helper, templates, context) { var params, hash; if (typeof helper === 'function') { params = getArrayValues(_params); hash = getHashValues(_hash); return { value: helper.call(context, params, hash, templates) }; } else if (helper.isLegacyViewHelper) { Ember['default'].assert('You can only pass attributes (such as name=value) not bare ' + 'values to a helper for a View found in \'' + helper.viewClass + '\'', _params.length === 0); env.hooks.keyword('view', morph, env, scope, [helper.viewClass], _hash, templates.template.raw, null, visitor); return { handled: true }; } else if (helper && helper.helperFunction) { var helperFunc = helper.helperFunction; return { value: helperFunc.call({}, _params, _hash, templates, env, scope) }; } } // We don't want to leak mutable cells into helpers, which // are pure functions that can only work with values. function getArrayValues(params) { var out = []; for (var i = 0, l = params.length; i < l; i++) { out.push(getValue['default'](params[i])); } return out; } function getHashValues(hash) { var out = {}; for (var prop in hash) { out[prop] = getValue['default'](hash[prop]); } return out; } }); enifed('ember-htmlbars/hooks/link-render-node', ['exports', 'ember-htmlbars/utils/subscribe', 'ember-runtime/utils', 'ember-metal/streams/utils', 'ember-htmlbars/system/lookup-helper'], function (exports, subscribe, utils, streams__utils, lookup_helper) { 'use strict'; exports['default'] = linkRenderNode; /** @module ember @submodule ember-htmlbars */ function linkRenderNode(renderNode, env, scope, path, params, hash) { if (renderNode.streamUnsubscribers) { return true; } var keyword = env.hooks.keywords[path]; var helper; if (keyword && keyword.link) { keyword.link(renderNode.state, params, hash); } else { switch (path) { case "unbound": return true; case "if": params[0] = shouldDisplay(params[0]);break; case "each": params[0] = eachParam(params[0]);break; default: helper = lookup_helper.findHelper(path, scope.view, env); if (helper && helper.isHandlebarsCompat && params[0]) { params[0] = processHandlebarsCompatDepKeys(params[0], helper._dependentKeys); } } } if (params && params.length) { for (var i = 0; i < params.length; i++) { subscribe['default'](renderNode, env, scope, params[i]); } } if (hash) { for (var key in hash) { subscribe['default'](renderNode, env, scope, hash[key]); } } // The params and hash can be reused; they don't need to be // recomputed on subsequent re-renders because they are // streams. return true; } function eachParam(list) { var listChange = getKey(list, "[]"); var stream = streams__utils.chain(list, function () { streams__utils.read(listChange); return streams__utils.read(list); }, "each"); stream.addDependency(listChange); return stream; } function shouldDisplay(predicate) { var length = getKey(predicate, "length"); var isTruthy = getKey(predicate, "isTruthy"); var stream = streams__utils.chain(predicate, function () { var predicateVal = streams__utils.read(predicate); var lengthVal = streams__utils.read(length); var isTruthyVal = streams__utils.read(isTruthy); if (utils.isArray(predicateVal)) { return lengthVal > 0; } if (typeof isTruthyVal === "boolean") { return isTruthyVal; } return !!predicateVal; }, "ShouldDisplay"); streams__utils.addDependency(stream, length); streams__utils.addDependency(stream, isTruthy); return stream; } function getKey(obj, key) { if (streams__utils.isStream(obj)) { return obj.getKey(key); } else { return obj && obj[key]; } } function processHandlebarsCompatDepKeys(base, additionalKeys) { if (!streams__utils.isStream(base) || additionalKeys.length === 0) { return base; } var depKeyStreams = []; var stream = streams__utils.chain(base, function () { streams__utils.readArray(depKeyStreams); return streams__utils.read(base); }, "HandlebarsCompatHelper"); for (var i = 0, l = additionalKeys.length; i < l; i++) { var depKeyStream = base.get(additionalKeys[i]); depKeyStreams.push(depKeyStream); stream.addDependency(depKeyStream); } return stream; } }); enifed('ember-htmlbars/hooks/lookup-helper', ['exports', 'ember-htmlbars/system/lookup-helper'], function (exports, lookupHelper) { 'use strict'; exports['default'] = lookupHelperHook; function lookupHelperHook(env, scope, helperName) { return lookupHelper['default'](helperName, scope.self, env); } }); enifed('ember-htmlbars/hooks/subexpr', ['exports', 'ember-htmlbars/system/lookup-helper', 'ember-metal/merge', 'ember-metal/streams/stream', 'ember-metal/platform/create', 'ember-metal/streams/utils'], function (exports, lookupHelper, merge, Stream, create, utils) { 'use strict'; exports['default'] = subexpr; /** @module ember @submodule ember-htmlbars */ function subexpr(env, scope, helperName, params, hash) { // TODO: Keywords and helper invocation should be integrated into // the subexpr hook upstream in HTMLBars. var keyword = env.hooks.keywords[helperName]; if (keyword) { return keyword(null, env, scope, params, hash, null, null); } var helper = lookupHelper['default'](helperName, scope.self, env); var invoker = function (params, hash) { return env.hooks.invokeHelper(null, env, scope, null, params, hash, helper, { template: {}, inverse: {} }, undefined).value; }; //Ember.assert("A helper named '"+helperName+"' could not be found", typeof helper === 'function'); var label = labelForSubexpr(params, hash, helperName); return new SubexprStream(params, hash, invoker, label); } function labelForSubexpr(params, hash, helperName) { return function () { var paramsLabels = labelsForParams(params); var hashLabels = labelsForHash(hash); var label = "(" + helperName; if (paramsLabels) { label += " " + paramsLabels; } if (hashLabels) { label += " " + hashLabels; } return "" + label + ")"; }; } function labelsForParams(params) { return utils.labelsFor(params).join(" "); } function labelsForHash(hash) { var out = []; for (var prop in hash) { out.push("" + prop + "=" + utils.labelFor(hash[prop])); } return out.join(" "); } function SubexprStream(params, hash, helper, label) { this.init(label); this.params = params; this.hash = hash; this.helper = helper; for (var i = 0, l = params.length; i < l; i++) { this.addDependency(params[i]); } for (var key in hash) { this.addDependency(hash[key]); } } SubexprStream.prototype = create['default'](Stream['default'].prototype); merge['default'](SubexprStream.prototype, { compute: function () { return this.helper(utils.readArray(this.params), utils.readHash(this.hash)); } }); }); enifed('ember-htmlbars/hooks/update-self', ['exports', 'ember-metal/property_get', 'ember-htmlbars/utils/update-scope'], function (exports, property_get, updateScope) { 'use strict'; exports['default'] = updateSelf; /** @module ember @submodule ember-htmlbars */ function updateSelf(env, scope, _self) { var self = _self; if (self && self.hasBoundController) { var controller = self.controller; self = self.self; updateScope['default'](scope.locals, "controller", controller || self); } Ember.assert("BUG: scope.attrs and self.isView should not both be true", !(scope.attrs && self.isView)); if (self && self.isView) { scope.view = self; updateScope['default'](scope.locals, "view", self, null); updateScope['default'](scope, "self", property_get.get(self, "context"), null, true); return; } updateScope['default'](scope, "self", self, null); } }); enifed('ember-htmlbars/hooks/will-cleanup-tree', ['exports'], function (exports) { 'use strict'; exports['default'] = willCleanupTree; function willCleanupTree(env, morph, destroySelf) { var view = morph.emberView; if (destroySelf && view && view.parentView) { view.parentView.removeChild(view); } if (view = env.view) { view.ownerView.isDestroyingSubtree = true; } } }); enifed('ember-htmlbars/keywords', ['exports', 'htmlbars-runtime', 'ember-metal/platform/create'], function (exports, htmlbars_runtime, o_create) { 'use strict'; exports.registerKeyword = registerKeyword; var keywords = o_create['default'](htmlbars_runtime.hooks.keywords); /** @module ember @submodule ember-htmlbars */ /** @private @method _registerHelper @for Ember.HTMLBars @param {String} name @param {Object|Function} helperFunc the helper function to add */ function registerKeyword(name, keyword) { keywords[name] = keyword; } exports['default'] = keywords; }); enifed('ember-htmlbars/keywords/collection', ['exports', 'ember-views/streams/utils', 'ember-views/views/collection_view', 'ember-htmlbars/node-managers/view-node-manager', 'ember-metal/keys', 'ember-metal/merge'], function (exports, utils, CollectionView, ViewNodeManager, objectKeys, merge) { 'use strict'; /** @module ember @submodule ember-htmlbars */ exports['default'] = { setupState: function (state, env, scope, params, hash) { var read = env.hooks.getValue; return merge.assign({}, state, { parentView: read(scope.locals.view), viewClassOrInstance: getView(read(params[0]), env.container) }); }, rerender: function (morph, env, scope, params, hash, template, inverse, visitor) { // If the hash is empty, the component cannot have extracted a part // of a mutable param and used it in its layout, because there are // no params at all. if (objectKeys['default'](hash).length) { return morph.state.manager.rerender(env, hash, visitor, true); } }, render: function (node, env, scope, params, hash, template, inverse, visitor) { var state = node.state; var parentView = state.parentView; var options = { component: node.state.viewClassOrInstance, layout: null }; if (template) { options.createOptions = { _itemViewTemplate: template && { raw: template }, _itemViewInverse: inverse && { raw: inverse } }; } if (hash.itemView) { hash.itemViewClass = hash.itemView; } if (hash.emptyView) { hash.emptyViewClass = hash.emptyView; } var nodeManager = ViewNodeManager['default'].create(node, env, hash, options, parentView, null, scope, template); state.manager = nodeManager; nodeManager.render(env, hash, visitor); } }; function getView(viewPath, container) { var viewClassOrInstance; if (!viewPath) { viewClassOrInstance = CollectionView['default']; } else { viewClassOrInstance = utils.readViewFactory(viewPath, container); } return viewClassOrInstance; } }); enifed('ember-htmlbars/keywords/component', ['exports', 'ember-metal/merge'], function (exports, merge) { 'use strict'; exports['default'] = { setupState: function (lastState, env, scope, params, hash) { var componentPath = env.hooks.getValue(params[0]); return merge.assign({}, lastState, { componentPath: componentPath, isComponentHelper: true }); }, render: function (morph) { for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { rest[_key - 1] = arguments[_key]; } // Force the component hook to treat this as a first-time render, // because normal components (``) cannot change at runtime, // but the `{{component}}` helper can. morph.state.manager = null; render.apply(undefined, [morph].concat(rest)); }, rerender: render }; function render(morph, env, scope, params, hash, template, inverse, visitor) { var componentPath = morph.state.componentPath; // If the value passed to the {{component}} helper is undefined or null, // don't create a new ComponentNode. if (componentPath === undefined || componentPath === null) { return; } env.hooks.component(morph, env, scope, componentPath, params, hash, { "default": template, inverse: inverse }, visitor); } }); enifed('ember-htmlbars/keywords/customized_outlet', ['exports', 'ember-htmlbars/node-managers/view-node-manager', 'ember-views/streams/utils', 'ember-metal/streams/utils'], function (exports, ViewNodeManager, utils, streams__utils) { 'use strict'; /** @module ember @submodule ember-htmlbars */ exports['default'] = { setupState: function (state, env, scope, params, hash) { Ember.assert("Using a quoteless view parameter with {{outlet}} is not supported", !hash.view || !streams__utils.isStream(hash.view)); var read = env.hooks.getValue; var viewClass = read(hash.viewClass) || utils.readViewFactory(read(hash.view), env.container); return { viewClass: viewClass }; }, render: function (renderNode, env, scope, params, hash, template, inverse, visitor) { var state = renderNode.state; var parentView = env.view; var options = { component: state.viewClass }; var nodeManager = ViewNodeManager['default'].create(renderNode, env, hash, options, parentView, null, null, null); state.manager = nodeManager; nodeManager.render(env, hash, visitor); } }; }); enifed('ember-htmlbars/keywords/debugger', ['exports', 'ember-metal/logger'], function (exports, Logger) { 'use strict'; exports['default'] = debuggerKeyword; /*jshint debug:true*/ /** @module ember @submodule ember-htmlbars */ function debuggerKeyword(morph, env, scope) { /* jshint unused: false, debug: true */ var view = env.hooks.getValue(scope.locals.view); var context = env.hooks.getValue(scope.self); function get(path) { return env.hooks.getValue(env.hooks.get(env, scope, path)); } Logger['default'].info("Use `view`, `context`, and `get()` to debug this template."); debugger; return true; } }); enifed('ember-htmlbars/keywords/each', ['exports', 'ember-runtime/controllers/array_controller'], function (exports, ArrayController) { 'use strict'; exports['default'] = each; /** @module ember @submodule ember-htmlbars */ function each(morph, env, scope, params, hash, template, inverse, visitor) { var getValue = env.hooks.getValue; var firstParam = params[0] && getValue(params[0]); var keyword = hash['-legacy-keyword'] && getValue(hash['-legacy-keyword']); if (firstParam && firstParam instanceof ArrayController['default']) { env.hooks.block(morph, env, scope, '-legacy-each-with-controller', params, hash, template, inverse, visitor); return true; } if (keyword) { env.hooks.block(morph, env, scope, '-legacy-each-with-keyword', params, hash, template, inverse, visitor); return true; } return false; } }); enifed('ember-htmlbars/keywords/input', ['exports', 'ember-metal/core', 'ember-metal/merge'], function (exports, Ember, merge) { 'use strict'; exports['default'] = { setupState: function (lastState, env, scope, params, hash) { var type = env.hooks.getValue(hash.type); var componentName = componentNameMap[type] || defaultComponentName; Ember['default'].assert("{{input type='checkbox'}} does not support setting `value=someBooleanValue`;" + " you must use `checked=someBooleanValue` instead.", !(type === "checkbox" && hash.hasOwnProperty("value"))); return merge.assign({}, lastState, { componentName: componentName }); }, render: function (morph, env, scope, params, hash, template, inverse, visitor) { env.hooks.component(morph, env, scope, morph.state.componentName, params, hash, { "default": template, inverse: inverse }, visitor); }, rerender: function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } this.render.apply(this, args); } }; var defaultComponentName = "-text-field"; var componentNameMap = { "checkbox": "-checkbox" }; }); enifed('ember-htmlbars/keywords/legacy-yield', ['exports', 'ember-metal/streams/proxy-stream'], function (exports, ProxyStream) { 'use strict'; exports['default'] = legacyYield; function legacyYield(morph, env, _scope, params, hash, template, inverse, visitor) { var scope = _scope; if (scope.blocks["default"].arity === 0) { // Typically, the `controller` local is persists through lexical scope. // However, in this case, the `{{legacy-yield}}` in the legacy each view // needs to override the controller local for the template it is yielding. // This megahaxx allows us to override the controller, and most importantly, // prevents the downstream scope from attempting to bind the `controller` local. if (hash.controller) { scope = env.hooks.createChildScope(scope); scope.locals.controller = new ProxyStream['default'](hash.controller, "controller"); scope.overrideController = true; } scope.blocks["default"](env, [], params[0], morph, scope, visitor); } else { scope.blocks["default"](env, params, undefined, morph, scope, visitor); } return true; } }); enifed('ember-htmlbars/keywords/mut', ['exports', 'ember-metal/platform/create', 'ember-metal/merge', 'ember-metal/utils', 'ember-metal/streams/proxy-stream', 'ember-metal/streams/utils', 'ember-metal/streams/stream', 'ember-views/compat/attrs-proxy', 'ember-routing-htmlbars/keywords/closure-action'], function (exports, create, merge, utils, ProxyStream, streams__utils, Stream, attrs_proxy, closure_action) { 'use strict'; exports.privateMut = privateMut; var _merge; exports['default'] = mut; var MUTABLE_REFERENCE = utils.symbol("MUTABLE_REFERENCE");function mut(morph, env, scope, originalParams, hash, template, inverse) { // If `morph` is `null` the keyword is being invoked as a subexpression. if (morph === null) { var valueStream = originalParams[0]; return mutParam(env.hooks.getValue, valueStream); } return true; } function privateMut(morph, env, scope, originalParams, hash, template, inverse) { // If `morph` is `null` the keyword is being invoked as a subexpression. if (morph === null) { var valueStream = originalParams[0]; return mutParam(env.hooks.getValue, valueStream, true); } return true; } function mutParam(read, stream, internal) { if (internal) { if (!streams__utils.isStream(stream)) { (function () { var literal = stream; stream = new Stream['default'](function () { return literal; }, "(literal " + literal + ")"); stream.setValue = function (newValue) { literal = newValue; stream.notify(); }; })(); } } else { Ember.assert("You can only pass a path to mut", streams__utils.isStream(stream)); } if (stream[MUTABLE_REFERENCE]) { return stream; } return new MutStream(stream); } function MutStream(stream) { this.init("(mut " + stream.label + ")"); this.path = stream.path; this.sourceDep = this.addMutableDependency(stream); this[MUTABLE_REFERENCE] = true; } MutStream.prototype = create['default'](ProxyStream['default'].prototype); merge['default'](MutStream.prototype, (_merge = {}, _merge.cell = function () { var source = this; var value = source.value(); if (value && value[closure_action.ACTION]) { return value; } var val = { value: value, update: function (val) { source.setValue(val); } }; val[attrs_proxy.MUTABLE_CELL] = true; return val; }, _merge[closure_action.INVOKE] = function (val) { this.setValue(val); }, _merge)); exports.MUTABLE_REFERENCE = MUTABLE_REFERENCE; }); enifed('ember-htmlbars/keywords/outlet', ['exports', 'htmlbars-runtime/hooks'], function (exports, hooks) { 'use strict'; /** @module ember @submodule ember-htmlbars */ exports['default'] = function (morph, env, scope, params, hash, template, inverse, visitor) { if (hash.hasOwnProperty('view') || hash.hasOwnProperty('viewClass')) { Ember.deprecate('Passing `view` or `viewClass` to {{outlet}} is deprecated.'); hooks.keyword('@customized_outlet', morph, env, scope, params, hash, template, inverse, visitor); } else { hooks.keyword('@real_outlet', morph, env, scope, params, hash, template, inverse, visitor); } return true; } }); enifed('ember-htmlbars/keywords/partial', ['exports', 'ember-views/system/lookup_partial', 'htmlbars-runtime'], function (exports, lookupPartial, htmlbars_runtime) { 'use strict'; /** @module ember @submodule ember-htmlbars */ exports['default'] = { setupState: function (state, env, scope, params, hash) { return { partialName: env.hooks.getValue(params[0]) }; }, render: function (renderNode, env, scope, params, hash, template, inverse, visitor) { var state = renderNode.state; if (!state.partialName) { return true; } var found = lookupPartial['default'](env, state.partialName); if (!found) { return true; } htmlbars_runtime.internal.hostBlock(renderNode, env, scope, found.raw, null, null, visitor, function (options) { options.templates.template.yield(); }); } }; }); enifed('ember-htmlbars/keywords/readonly', ['exports', 'ember-htmlbars/keywords/mut'], function (exports, mut) { 'use strict'; exports['default'] = readonly; function readonly(morph, env, scope, originalParams, hash, template, inverse) { // If `morph` is `null` the keyword is being invoked as a subexpression. if (morph === null) { var stream = originalParams[0]; if (stream && stream[mut.MUTABLE_REFERENCE]) { return stream.sourceDep.dependee; } return stream; } return true; } }); enifed('ember-htmlbars/keywords/real_outlet', ['exports', 'ember-metal/property_get', 'ember-htmlbars/node-managers/view-node-manager', 'ember-htmlbars/templates/top-level-view'], function (exports, property_get, ViewNodeManager, topLevelViewTemplate) { 'use strict'; /** @module ember @submodule ember-htmlbars */ topLevelViewTemplate['default'].meta.revision = "Ember@1.13.0-beta.2"; exports['default'] = { willRender: function (renderNode, env) { env.view.ownerView._outlets.push(renderNode); }, setupState: function (state, env, scope, params, hash) { var outletState = env.outletState; var read = env.hooks.getValue; var outletName = read(params[0]) || "main"; var selectedOutletState = outletState[outletName]; var toRender = selectedOutletState && selectedOutletState.render; if (toRender && !toRender.template && !toRender.ViewClass) { toRender.template = topLevelViewTemplate['default']; } return { outletState: selectedOutletState, hasParentOutlet: env.hasParentOutlet }; }, childEnv: function (state) { return { outletState: state.outletState && state.outletState.outlets, hasParentOutlet: true }; }, isStable: function (lastState, nextState) { return isStable(lastState.outletState, nextState.outletState); }, isEmpty: function (state) { return isEmpty(state.outletState); }, render: function (renderNode, env, scope, params, hash, template, inverse, visitor) { var state = renderNode.state; var parentView = env.view; var outletState = state.outletState; var toRender = outletState.render; var namespace = env.container.lookup("application:main"); var LOG_VIEW_LOOKUPS = property_get.get(namespace, "LOG_VIEW_LOOKUPS"); var ViewClass = outletState.render.ViewClass; if (!state.hasParentOutlet && !ViewClass) { ViewClass = env.container.lookupFactory("view:toplevel"); } var options = { component: ViewClass, self: toRender.controller, createOptions: { controller: toRender.controller } }; template = template || toRender.template && toRender.template.raw; if (LOG_VIEW_LOOKUPS && ViewClass) { Ember.Logger.info("Rendering " + toRender.name + " with " + ViewClass, { fullName: "view:" + toRender.name }); } var nodeManager = ViewNodeManager['default'].create(renderNode, env, {}, options, parentView, null, null, template); state.manager = nodeManager; nodeManager.render(env, hash, visitor); } }; function isEmpty(outletState) { return !outletState || !outletState.render.ViewClass && !outletState.render.template; } function isStable(a, b) { if (!a && !b) { return true; } if (!a || !b) { return false; } a = a.render; b = b.render; for (var key in a) { if (a.hasOwnProperty(key)) { // name is only here for logging & debugging. If two different // names result in otherwise identical states, they're still // identical. if (a[key] !== b[key] && key !== "name") { return false; } } } return true; } }); enifed('ember-htmlbars/keywords/template', ['exports', 'ember-metal/core'], function (exports, Ember) { 'use strict'; exports['default'] = templateKeyword; var deprecation = "The `template` helper has been deprecated in favor of the `partial` helper.";function templateKeyword(morph, env, scope, params, hash, template, inverse, visitor) { Ember['default'].deprecate(deprecation); env.hooks.keyword("partial", morph, env, scope, params, hash, template, inverse, visitor); return true; } exports.deprecation = deprecation; }); enifed('ember-htmlbars/keywords/textarea', ['exports'], function (exports) { 'use strict'; exports['default'] = textarea; /** @module ember @submodule ember-htmlbars */ function textarea(morph, env, scope, originalParams, hash, template, inverse, visitor) { env.hooks.component(morph, env, scope, '-text-area', originalParams, hash, { "default": template, inverse: inverse }, visitor); return true; } }); enifed('ember-htmlbars/keywords/unbound', ['exports', 'ember-metal/merge', 'ember-metal/platform/create', 'ember-metal/streams/stream', 'ember-metal/streams/utils'], function (exports, merge, create, Stream, utils) { 'use strict'; exports['default'] = unbound; function unbound(morph, env, scope, originalParams, hash, template, inverse) { // Since we already got the params as a set of streams, we need to extract the key from // the first param instead of (incorrectly) trying to read from it. If this was a call // to `{{unbound foo.bar}}`, then we pass along the original stream to `hooks.range`. var params = originalParams.slice(); var valueStream = params.shift(); // If `morph` is `null` the keyword is being invoked as a subexpression. if (morph === null) { if (originalParams.length > 1) { valueStream = env.hooks.subexpr(env, scope, valueStream.key, params, hash); } return new VolatileStream(valueStream); } if (params.length === 0) { env.hooks.range(morph, env, scope, null, valueStream); } else if (template === null) { env.hooks.inline(morph, env, scope, valueStream.key, params, hash); } else { env.hooks.block(morph, env, scope, valueStream.key, params, hash, template, inverse); } return true; } function VolatileStream(source) { this.init("(volatile " + source.label + ")"); this.source = source; this.addDependency(source); } VolatileStream.prototype = create['default'](Stream['default'].prototype); merge['default'](VolatileStream.prototype, { value: function () { return utils.read(this.source); }, notify: function () {} }); }); enifed('ember-htmlbars/keywords/view', ['exports', 'ember-views/streams/utils', 'ember-views/views/view', 'ember-htmlbars/node-managers/view-node-manager', 'ember-metal/keys'], function (exports, utils, EmberView, ViewNodeManager, objectKeys) { 'use strict'; /** @module ember @submodule ember-htmlbars */ exports['default'] = { setupState: function (state, env, scope, params, hash) { var read = env.hooks.getValue; var targetObject = read(scope.self); var viewClassOrInstance = state.viewClassOrInstance; if (!viewClassOrInstance) { viewClassOrInstance = getView(read(params[0]), env.container); } // if parentView exists, use its controller (the default // behavior), otherwise use `scope.self` as the controller var controller = scope.view ? null : read(scope.self); return { manager: state.manager, parentView: scope.view, controller: controller, targetObject: targetObject, viewClassOrInstance: viewClassOrInstance }; }, rerender: function (morph, env, scope, params, hash, template, inverse, visitor) { // If the hash is empty, the component cannot have extracted a part // of a mutable param and used it in its layout, because there are // no params at all. if (objectKeys['default'](hash).length) { return morph.state.manager.rerender(env, hash, visitor, true); } }, render: function (node, env, scope, params, hash, template, inverse, visitor) { if (hash.tag) { hash = swapKey(hash, "tag", "tagName"); } if (hash.classNameBindings) { hash.classNameBindings = hash.classNameBindings.split(" "); } var state = node.state; var parentView = state.parentView; var options = { component: node.state.viewClassOrInstance, layout: null }; options.createOptions = {}; if (node.state.controller) { // Use `_controller` to avoid stomping on a CP // that exists in the target view/component options.createOptions._controller = node.state.controller; } if (node.state.targetObject) { // Use `_targetObject` to avoid stomping on a CP // that exists in the target view/component options.createOptions._targetObject = node.state.targetObject; } var nodeManager = ViewNodeManager['default'].create(node, env, hash, options, parentView, null, scope, template); state.manager = nodeManager; nodeManager.render(env, hash, visitor); } }; function getView(viewPath, container) { var viewClassOrInstance; if (!viewPath) { if (container) { viewClassOrInstance = container.lookupFactory("view:toplevel"); } else { viewClassOrInstance = EmberView['default']; } } else { viewClassOrInstance = utils.readViewFactory(viewPath, container); } return viewClassOrInstance; } function swapKey(hash, original, update) { var newHash = {}; for (var prop in hash) { if (prop === original) { newHash[update] = hash[prop]; } else { newHash[prop] = hash[prop]; } } return newHash; } }); enifed('ember-htmlbars/keywords/with', ['exports', 'htmlbars-runtime', 'ember-metal/property_get'], function (exports, htmlbars_runtime, property_get) { 'use strict'; exports['default'] = { setupState: function (state, env, scope, params, hash) { var controller = hash.controller; if (controller) { if (!state.controller) { var context = params[0]; var controllerFactory = env.container.lookupFactory("controller:" + controller); var parentController = scope.view ? property_get.get(scope.view, "context") : null; var controllerInstance = controllerFactory.create({ model: env.hooks.getValue(context), parentController: parentController, target: parentController }); params[0] = controllerInstance; return { controller: controllerInstance }; } return state; } return { controller: null }; }, isStable: function () { return true; }, isEmpty: function (state) { return false; }, render: function (morph, env, scope, params, hash, template, inverse, visitor) { if (morph.state.controller) { morph.addDestruction(morph.state.controller); hash.controller = morph.state.controller; } Ember.assert("{{#with foo}} must be called with a single argument or the use the " + "{{#with foo as bar}} syntax", params.length === 1); Ember.assert("The {{#with}} helper must be called with a block", !!template); if (template && template.arity === 0) { Ember.deprecate("Using the context switching form of `{{with}}` is deprecated. " + "Please use the block param form (`{{#with bar as |foo|}}`) instead.", false, { url: "http://emberjs.com/guides/deprecations/#toc_more-consistent-handlebars-scope" }); } htmlbars_runtime.internal.continueBlock(morph, env, scope, "with", params, hash, template, inverse, visitor); }, rerender: function (morph, env, scope, params, hash, template, inverse, visitor) { htmlbars_runtime.internal.continueBlock(morph, env, scope, "with", params, hash, template, inverse, visitor); } }; }); enifed('ember-htmlbars/morphs/attr-morph', ['exports', 'ember-metal/core', 'dom-helper', 'ember-metal/platform/create'], function (exports, Ember, DOMHelper, o_create) { 'use strict'; var HTMLBarsAttrMorph = DOMHelper['default'].prototype.AttrMorphClass; var styleWarning = "" + "Binding style attributes may introduce cross-site scripting vulnerabilities; " + "please ensure that values being bound are properly escaped. For more information, " + "including how to disable this warning, see " + "http://emberjs.com/deprecations/v1.x/#toc_binding-style-attributes."; function EmberAttrMorph(element, attrName, domHelper, namespace) { HTMLBarsAttrMorph.call(this, element, attrName, domHelper, namespace); } var proto = EmberAttrMorph.prototype = o_create['default'](HTMLBarsAttrMorph.prototype); proto.HTMLBarsAttrMorph$setContent = HTMLBarsAttrMorph.prototype.setContent; proto._deprecateEscapedStyle = function EmberAttrMorph_deprecateEscapedStyle(value) { Ember['default'].warn(styleWarning, (function (name, value, escaped) { // SafeString if (value && value.toHTML) { return true; } if (name !== "style") { return true; } return !escaped; })(this.attrName, value, this.escaped)); }; proto.setContent = function EmberAttrMorph_setContent(value) { this._deprecateEscapedStyle(value); this.HTMLBarsAttrMorph$setContent(value); }; exports['default'] = EmberAttrMorph; exports.styleWarning = styleWarning; }); enifed('ember-htmlbars/morphs/morph', ['exports', 'dom-helper', 'ember-metal/platform/create'], function (exports, dom_helper, o_create) { 'use strict'; var HTMLBarsMorph = dom_helper['default'].prototype.MorphClass; var guid = 1; function EmberMorph(DOMHelper, contextualElement) { this.HTMLBarsMorph$constructor(DOMHelper, contextualElement); this.emberView = null; this.emberToDestroy = null; this.streamUnsubscribers = null; this.guid = guid++; // A component can become dirty either because one of its // attributes changed, or because it was re-rendered. If any part // of the component's template changes through observation, it has // re-rendered from the perpsective of the programming model. This // flag is set to true whenever a component becomes dirty because // one of its attributes changed, which also triggers the attribute // update flag (didUpdateAttrs). this.shouldReceiveAttrs = false; } var proto = EmberMorph.prototype = o_create['default'](HTMLBarsMorph.prototype); proto.HTMLBarsMorph$constructor = HTMLBarsMorph; proto.HTMLBarsMorph$clear = HTMLBarsMorph.prototype.clear; proto.addDestruction = function (toDestroy) { this.emberToDestroy = this.emberToDestroy || []; this.emberToDestroy.push(toDestroy); }; proto.cleanup = function () { var view; if (view = this.emberView) { if (!view.ownerView.isDestroyingSubtree) { view.ownerView.isDestroyingSubtree = true; if (view.parentView) { view.parentView.removeChild(view); } } } var toDestroy = this.emberToDestroy; if (toDestroy) { for (var i = 0, l = toDestroy.length; i < l; i++) { toDestroy[i].destroy(); } this.emberToDestroy = null; } }; proto.didRender = function (env, scope) { env.renderedNodes[this.guid] = true; }; exports['default'] = EmberMorph; }); enifed('ember-htmlbars/node-managers/component-node-manager', ['exports', 'ember-metal/core', 'ember-metal/merge', 'ember-views/system/build-component-template', 'ember-htmlbars/utils/lookup-component', 'ember-htmlbars/hooks/get-cell-or-value', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/set_properties', 'ember-views/compat/attrs-proxy', 'htmlbars-util/safe-string', 'ember-htmlbars/system/instrumentation-support', 'ember-views/views/component', 'ember-htmlbars/hooks/get-value'], function (exports, Ember, merge, buildComponentTemplate, lookupComponent, getCellOrValue, property_get, property_set, setProperties, attrs_proxy, SafeString, instrumentation_support, EmberComponent, getValue) { 'use strict'; exports.handleLegacyRender = handleLegacyRender; exports.createComponent = createComponent; function ComponentNodeManager(component, isAngleBracket, scope, renderNode, attrs, block, expectElement) { this.component = component; this.isAngleBracket = isAngleBracket; this.scope = scope; this.renderNode = renderNode; this.attrs = attrs; this.block = block; this.expectElement = expectElement; } exports['default'] = ComponentNodeManager; ComponentNodeManager.create = function (renderNode, env, options) { var tagName = options.tagName; var params = options.params; var attrs = options.attrs; var parentView = options.parentView; var parentScope = options.parentScope; var isAngleBracket = options.isAngleBracket; var templates = options.templates; attrs = attrs || {}; // Try to find the Component class and/or template for this component name in // the container. var _lookupComponent = lookupComponent['default'](env.container, tagName); var component = _lookupComponent.component; var layout = _lookupComponent.layout; Ember['default'].assert("HTMLBars error: Could not find component named \"" + tagName + "\" (no component or template with that name was found)", function () { return component || layout; }); component = component || EmberComponent['default']; var createOptions = { parentView: parentView }; configureTagName(attrs, tagName, component, isAngleBracket, createOptions); // Map passed attributes (e.g. ) to component // properties ({ id: "foo" }). configureCreateOptions(attrs, createOptions); // If there is a controller on the scope, pluck it off and save it on the // component. This allows the component to target actions sent via // `sendAction` correctly. if (parentScope.locals.controller) { createOptions._controller = getValue['default'](parentScope.locals.controller); } // Instantiate the component component = createComponent(component, isAngleBracket, createOptions, renderNode, env, attrs); // If the component specifies its template via the `layout` or `template` // properties instead of using the template looked up in the container, get // them now that we have the component instance. var result = extractComponentTemplates(component, templates); layout = result.layout || layout; templates = result.templates || templates; extractPositionalParams(renderNode, component, params, attrs); var results = buildComponentTemplate['default']({ layout: layout, component: component, isAngleBracket: isAngleBracket }, attrs, { templates: templates, scope: parentScope }); return new ComponentNodeManager(component, isAngleBracket, parentScope, renderNode, attrs, results.block, results.createdElement); }; function extractPositionalParams(renderNode, component, params, attrs) { if (component.positionalParams) { // if the component is rendered via {{component}} helper, the first // element of `params` is the name of the component, so we need to // skip that when the positional parameters are constructed var paramsStartIndex = renderNode.state.isComponentHelper ? 1 : 0; var pp = component.positionalParams; for (var i = 0; i < pp.length; i++) { attrs[pp[i]] = params[paramsStartIndex + i]; } } } function extractComponentTemplates(component, _templates) { // Even though we looked up a layout from the container earlier, the // component may specify a `layout` property that overrides that. // The component may also provide a `template` property we should // respect (though this behavior is deprecated). var componentLayout = property_get.get(component, "layout"); var componentTemplate = property_get.get(component, "template"); var layout = undefined, templates = undefined; if (componentLayout) { layout = componentLayout; templates = extractLegacyTemplate(_templates, componentTemplate); } else if (componentTemplate) { // If the component has a `template` but no `layout`, use the template // as the layout. layout = componentTemplate; templates = _templates; Ember['default'].deprecate("Using deprecated `template` property on a Component."); } return { layout: layout, templates: templates }; } // 2.0TODO: Remove legacy behavior function extractLegacyTemplate(_templates, componentTemplate) { var templates = undefined; // There is no block template provided but the component has a // `template` property. if ((!templates || !templates["default"]) && componentTemplate) { Ember['default'].deprecate("Using deprecated `template` property on a Component."); templates = { "default": componentTemplate.raw }; } else { templates = _templates; } return templates; } function configureTagName(attrs, tagName, component, isAngleBracket, createOptions) { if (isAngleBracket) { createOptions.tagName = tagName; } else if (attrs.tagName) { createOptions.tagName = getValue['default'](attrs.tagName); } } function configureCreateOptions(attrs, createOptions) { // Some attrs are special and need to be set as properties on the component // instance. Make sure we use getValue() to get them from `attrs` since // they are still streams. if (attrs.id) { createOptions.elementId = getValue['default'](attrs.id); } if (attrs._defaultTagName) { createOptions._defaultTagName = getValue['default'](attrs._defaultTagName); } if (attrs.viewName) { createOptions.viewName = getValue['default'](attrs.viewName); } } ComponentNodeManager.prototype.render = function (_env, visitor) { var component = this.component; var attrs = this.attrs; return instrumentation_support.instrument(component, function () { var env = _env; env = merge.assign({ view: component }, env); var snapshot = takeSnapshot(attrs); env.renderer.componentInitAttrs(this.component, snapshot); env.renderer.componentWillRender(component); env.renderedViews.push(component.elementId); if (this.block) { this.block(env, [], undefined, this.renderNode, this.scope, visitor); } var element = this.expectElement && this.renderNode.firstNode; handleLegacyRender(component, element); env.renderer.didCreateElement(component, element); env.renderer.willInsertElement(component, element); // 2.0TODO remove legacy hook env.lifecycleHooks.push({ type: "didInsertElement", view: component }); }, this); }; function handleLegacyRender(component, element) { if (!component.render) { return; } Ember['default'].assert("Legacy render functions are not supported with angle-bracket components", !component._isAngleBracket); var content, node, lastChildIndex; var buffer = []; var renderNode = component._renderNode; component.render(buffer); content = buffer.join(""); if (element) { lastChildIndex = renderNode.childNodes.length - 1; node = renderNode.childNodes[lastChildIndex]; } else { node = renderNode; } node.setContent(new SafeString['default'](content)); } ComponentNodeManager.prototype.rerender = function (_env, attrs, visitor) { var component = this.component; return instrumentation_support.instrument(component, function () { var env = _env; env = merge.assign({ view: component }, env); var snapshot = takeSnapshot(attrs); if (component._renderNode.shouldReceiveAttrs) { env.renderer.componentUpdateAttrs(component, component.attrs, snapshot); if (!component._isAngleBracket) { setProperties['default'](component, mergeBindings({}, shadowedAttrs(component, snapshot))); } component._renderNode.shouldReceiveAttrs = false; } // Notify component that it has become dirty and is about to change. env.renderer.componentWillUpdate(component, snapshot); env.renderer.componentWillRender(component); env.renderedViews.push(component.elementId); if (this.block) { this.block(env, [], undefined, this.renderNode, this.scope, visitor); } env.lifecycleHooks.push({ type: "didUpdate", view: component }); return env; }, this); }; function createComponent(_component, isAngleBracket, _props, renderNode, env) { var attrs = arguments[5] === undefined ? {} : arguments[5]; var props = merge.assign({}, _props); if (!isAngleBracket) { var hasSuppliedController = ("controller" in attrs); // 2.0TODO remove Ember['default'].deprecate("controller= is deprecated", !hasSuppliedController); var snapshot = takeSnapshot(attrs); props.attrs = snapshot; var proto = _component.proto(); mergeBindings(props, shadowedAttrs(proto, snapshot)); } else { props._isAngleBracket = true; } var component = _component.create(props); // for the fallback case component.container = component.container || env.container; if (props.parentView) { props.parentView.appendChild(component); if (props.viewName) { property_set.set(props.parentView, props.viewName, component); } } component._renderNode = renderNode; renderNode.emberView = component; return component; } function shadowedAttrs(target, attrs) { var shadowed = {}; // For backwards compatibility, set the component property // if it has an attr with that name. Undefined attributes // are handled on demand via the `unknownProperty` hook. for (var attr in attrs) { if (attr in target) { // TODO: Should we issue a deprecation here? //Ember.deprecate(deprecation(attr)); shadowed[attr] = attrs[attr]; } } return shadowed; } function takeSnapshot(attrs) { var hash = {}; for (var prop in attrs) { hash[prop] = getCellOrValue['default'](attrs[prop]); } return hash; } function mergeBindings(target, attrs) { for (var prop in attrs) { if (!attrs.hasOwnProperty(prop)) { continue; } // when `attrs` is an actual value being set in the // attrs hash (`{{foo-bar attrs="blah"}}`) we cannot // set `"blah"` to the root of the target because // that would replace all attrs with `attrs.attrs` if (prop === "attrs") { Ember['default'].warn("Invoking a component with a hash attribute named `attrs` is not supported. Please refactor usage of " + target + " to avoid passing `attrs` as a hash parameter."); continue; } var value = attrs[prop]; if (value && value[attrs_proxy.MUTABLE_CELL]) { target[prop] = value.value; } else { target[prop] = value; } } return target; } }); enifed('ember-htmlbars/node-managers/view-node-manager', ['exports', 'ember-metal/merge', 'ember-metal/core', 'ember-views/system/build-component-template', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/set_properties', 'ember-views/views/view', 'ember-views/compat/attrs-proxy', 'ember-htmlbars/hooks/get-cell-or-value', 'ember-htmlbars/system/instrumentation-support', 'ember-htmlbars/node-managers/component-node-manager', 'ember-htmlbars/hooks/get-value'], function (exports, merge, Ember, buildComponentTemplate, property_get, property_set, setProperties, View, attrs_proxy, getCellOrValue, instrumentation_support, component_node_manager, getValue) { 'use strict'; exports.createOrUpdateComponent = createOrUpdateComponent; function ViewNodeManager(component, scope, renderNode, block, expectElement) { this.component = component; this.scope = scope; this.renderNode = renderNode; this.block = block; this.expectElement = expectElement; } exports['default'] = ViewNodeManager; ViewNodeManager.create = function (renderNode, env, attrs, found, parentView, path, contentScope, contentTemplate) { Ember['default'].assert("HTMLBars error: Could not find component named \"" + path + "\" (no component or template with that name was found)", function () { if (path) { return found.component || found.layout; } else { return found.component || found.layout || contentTemplate; } }); var component; var componentInfo = { layout: found.layout }; if (found.component) { var options = { parentView: parentView }; if (attrs && attrs.id) { options.elementId = getValue['default'](attrs.id); } if (attrs && attrs.tagName) { options.tagName = getValue['default'](attrs.tagName); } if (attrs && attrs._defaultTagName) { options._defaultTagName = getValue['default'](attrs._defaultTagName); } if (attrs && attrs.viewName) { options.viewName = getValue['default'](attrs.viewName); } if (found.component.create && contentScope && contentScope.self) { options._context = getValue['default'](contentScope.self); } if (found.self) { options._context = getValue['default'](found.self); } component = componentInfo.component = createOrUpdateComponent(found.component, options, found.createOptions, renderNode, env, attrs); var layout = property_get.get(component, "layout"); if (layout) { componentInfo.layout = layout; if (!contentTemplate) { var template = property_get.get(component, "template"); if (template) { Ember['default'].deprecate("Using deprecated `template` property on a " + (component.isView ? "View" : "Component") + "."); contentTemplate = template.raw; } } } else { componentInfo.layout = property_get.get(component, "template") || componentInfo.layout; } renderNode.emberView = component; } Ember['default'].assert("BUG: ViewNodeManager.create can take a scope or a self, but not both", !(contentScope && found.self)); var results = buildComponentTemplate['default'](componentInfo, attrs, { templates: { "default": contentTemplate }, scope: contentScope, self: found.self }); return new ViewNodeManager(component, contentScope, renderNode, results.block, results.createdElement); }; ViewNodeManager.prototype.render = function (env, attrs, visitor) { var component = this.component; return instrumentation_support.instrument(component, function () { var newEnv = env; if (component) { newEnv = merge['default']({}, env); newEnv.view = component; } if (component) { var snapshot = takeSnapshot(attrs); env.renderer.setAttrs(this.component, snapshot); env.renderer.willCreateElement(component); env.renderer.willRender(component); env.renderedViews.push(component.elementId); } if (this.block) { this.block(newEnv, [], undefined, this.renderNode, this.scope, visitor); } if (component) { var element = this.expectElement && this.renderNode.firstNode; component_node_manager.handleLegacyRender(component, element); env.renderer.didCreateElement(component, element); // 2.0TODO: Remove legacy hooks. env.renderer.willInsertElement(component, element); env.lifecycleHooks.push({ type: "didInsertElement", view: component }); } }, this); }; ViewNodeManager.prototype.rerender = function (env, attrs, visitor) { var component = this.component; return instrumentation_support.instrument(component, function () { var newEnv = env; if (component) { newEnv = merge['default']({}, env); newEnv.view = component; var snapshot = takeSnapshot(attrs); // Notify component that it has become dirty and is about to change. env.renderer.willUpdate(component, snapshot); if (component._renderNode.shouldReceiveAttrs) { env.renderer.updateAttrs(component, snapshot); setProperties['default'](component, mergeBindings({}, shadowedAttrs(component, snapshot))); component._renderNode.shouldReceiveAttrs = false; } env.renderer.willRender(component); env.renderedViews.push(component.elementId); } if (this.block) { this.block(newEnv, [], undefined, this.renderNode, this.scope, visitor); } if (component) { env.lifecycleHooks.push({ type: "didUpdate", view: component }); } return newEnv; }, this); }; function createOrUpdateComponent(component, options, createOptions, renderNode, env) { var attrs = arguments[5] === undefined ? {} : arguments[5]; var snapshot = takeSnapshot(attrs); var props = merge['default']({}, options); var defaultController = View['default'].proto().controller; var hasSuppliedController = "controller" in attrs || "controller" in props; props.attrs = snapshot; if (component.create) { var proto = component.proto(); if (createOptions) { merge['default'](props, createOptions); } mergeBindings(props, shadowedAttrs(proto, snapshot)); props.container = options.parentView ? options.parentView.container : env.container; if (proto.controller !== defaultController || hasSuppliedController) { delete props._context; } component = component.create(props); } else { mergeBindings(props, shadowedAttrs(component, snapshot)); setProperties['default'](component, props); } if (options.parentView) { options.parentView.appendChild(component); if (options.viewName) { property_set.set(options.parentView, options.viewName, component); } } component._renderNode = renderNode; renderNode.emberView = component; return component; } function shadowedAttrs(target, attrs) { var shadowed = {}; // For backwards compatibility, set the component property // if it has an attr with that name. Undefined attributes // are handled on demand via the `unknownProperty` hook. for (var attr in attrs) { if (attr in target) { // TODO: Should we issue a deprecation here? //Ember.deprecate(deprecation(attr)); shadowed[attr] = attrs[attr]; } } return shadowed; } function takeSnapshot(attrs) { var hash = {}; for (var prop in attrs) { hash[prop] = getCellOrValue['default'](attrs[prop]); } return hash; } function mergeBindings(target, attrs) { for (var prop in attrs) { if (!attrs.hasOwnProperty(prop)) { continue; } // when `attrs` is an actual value being set in the // attrs hash (`{{foo-bar attrs="blah"}}`) we cannot // set `"blah"` to the root of the target because // that would replace all attrs with `attrs.attrs` if (prop === "attrs") { Ember['default'].warn("Invoking a component with a hash attribute named `attrs` is not supported. Please refactor usage of " + target + " to avoid passing `attrs` as a hash parameter."); continue; } var value = attrs[prop]; if (value && value[attrs_proxy.MUTABLE_CELL]) { target[prop] = value.value; } else { target[prop] = value; } } return target; } }); enifed('ember-htmlbars/system/append-templated-view', ['exports', 'ember-metal/core', 'ember-metal/property_get', 'ember-views/views/view'], function (exports, Ember, property_get, View) { 'use strict'; exports['default'] = appendTemplatedView; /** @module ember @submodule ember-htmlbars */ function appendTemplatedView(parentView, morph, viewClassOrInstance, props) { var viewProto; if (View['default'].detectInstance(viewClassOrInstance)) { viewProto = viewClassOrInstance; } else { viewProto = viewClassOrInstance.proto(); } Ember['default'].assert("You cannot provide a template block if you also specified a templateName", !props.template || !property_get.get(props, "templateName") && !property_get.get(viewProto, "templateName")); // We only want to override the `_context` computed property if there is // no specified controller. See View#_context for more information. var noControllerInProto = !viewProto.controller; if (viewProto.controller && viewProto.controller.isDescriptor) { noControllerInProto = true; } if (noControllerInProto && !viewProto.controllerBinding && !props.controller && !props.controllerBinding) { props._context = property_get.get(parentView, "context"); // TODO: is this right?! } props._morph = morph; return parentView.appendChild(viewClassOrInstance, props); } }); enifed('ember-htmlbars/system/bootstrap', ['exports', 'ember-metal/core', 'ember-views/component_lookup', 'ember-views/system/jquery', 'ember-metal/error', 'ember-runtime/system/lazy_load', 'ember-template-compiler/system/compile', 'ember-metal/environment'], function (exports, Ember, ComponentLookup, jQuery, EmberError, lazy_load, htmlbarsCompile, environment) { 'use strict'; /*globals Handlebars */ /** @module ember @submodule ember-htmlbars */ function bootstrap(ctx) { var selectors = "script[type=\"text/x-handlebars\"], script[type=\"text/x-raw-handlebars\"]"; jQuery['default'](selectors, ctx).each(function () { // Get a reference to the script tag var script = jQuery['default'](this); // Get the name of the script, used by Ember.View's templateName property. // First look for data-template-name attribute, then fall back to its // id if no name is found. var templateName = script.attr("data-template-name") || script.attr("id") || "application"; var template, compile; if (script.attr("type") === "text/x-raw-handlebars") { compile = jQuery['default'].proxy(Handlebars.compile, Handlebars); template = compile(script.html()); } else { template = htmlbarsCompile['default'](script.html(), { moduleName: templateName }); } // Check if template of same name already exists if (Ember['default'].TEMPLATES[templateName] !== undefined) { throw new EmberError['default']("Template named \"" + templateName + "\" already exists."); } // For templates which have a name, we save them and then remove them from the DOM Ember['default'].TEMPLATES[templateName] = template; // Remove script tag from DOM script.remove(); }); } function _bootstrap() { bootstrap(jQuery['default'](document)); } function registerComponentLookup(registry) { registry.register("component-lookup:main", ComponentLookup['default']); } /* We tie this to application.load to ensure that we've at least attempted to bootstrap at the point that the application is loaded. We also tie this to document ready since we're guaranteed that all the inline templates are present at this point. There's no harm to running this twice, since we remove the templates from the DOM after processing. */ lazy_load.onLoad("Ember.Application", function (Application) { Application.initializer({ name: "domTemplates", initialize: environment['default'].hasDOM ? _bootstrap : function () {} }); Application.initializer({ name: "registerComponentLookup", after: "domTemplates", initialize: registerComponentLookup }); }); exports['default'] = bootstrap; }); enifed('ember-htmlbars/system/dom-helper', ['exports', 'dom-helper', 'ember-htmlbars/morphs/morph', 'ember-htmlbars/morphs/attr-morph', 'ember-metal/platform/create'], function (exports, DOMHelper, EmberMorph, EmberAttrMorph, o_create) { 'use strict'; function EmberDOMHelper(_document) { DOMHelper['default'].call(this, _document); } var proto = EmberDOMHelper.prototype = o_create['default'](DOMHelper['default'].prototype); proto.MorphClass = EmberMorph['default']; proto.AttrMorphClass = EmberAttrMorph['default']; exports['default'] = EmberDOMHelper; }); enifed('ember-htmlbars/system/helper', ['exports'], function (exports) { 'use strict'; /** @module ember @submodule ember-htmlbars */ /** @class Helper @namespace Ember.HTMLBars */ function Helper(helper) { this.helperFunction = helper; this.isHelper = true; this.isHTMLBars = true; } exports['default'] = Helper; }); enifed('ember-htmlbars/system/instrumentation-support', ['exports', 'ember-metal/instrumentation'], function (exports, instrumentation) { 'use strict'; exports.instrument = instrument; function instrument(component, callback, context) { var instrumentName, val, details, end; // Only instrument if there's at least one subscriber. if (instrumentation.subscribers.length) { if (component) { instrumentName = component.instrumentName; } else { instrumentName = 'node'; } details = {}; if (component) { component.instrumentDetails(details); } end = instrumentation._instrumentStart('render.' + instrumentName, function viewInstrumentDetails() { return details; }); val = callback.call(context); if (end) { end(); } return val; } else { return callback.call(context); } } }); enifed('ember-htmlbars/system/lookup-helper', ['exports', 'ember-metal/core', 'ember-metal/cache', 'ember-htmlbars/system/make-view-helper', 'ember-htmlbars/compat/helper'], function (exports, Ember, Cache, makeViewHelper, HandlebarsCompatibleHelper) { 'use strict'; exports.findHelper = findHelper; exports['default'] = lookupHelper; /** @module ember @submodule ember-htmlbars */ var ISNT_HELPER_CACHE = new Cache['default'](1000, function (key) { return key.indexOf("-") === -1; }); function findHelper(name, view, env) { var helper = env.helpers[name]; if (helper) { return helper; } var container = env.container; if (!container || ISNT_HELPER_CACHE.get(name)) { return; } if (name in env.hooks.keywords) { return; } var helperName = "helper:" + name; helper = container.lookup(helperName); if (!helper) { var componentLookup = container.lookup("component-lookup:main"); Ember['default'].assert("Could not find 'component-lookup:main' on the provided container," + " which is necessary for performing component lookups", componentLookup); var Component = componentLookup.lookupFactory(name, container); if (Component) { helper = makeViewHelper['default'](Component); container._registry.register(helperName, helper); } } if (helper && !helper.isHTMLBars) { helper = new HandlebarsCompatibleHelper['default'](helper); container._registry.unregister(helperName); container._registry.register(helperName, helper); } return helper; } function lookupHelper(name, view, env) { var helper = findHelper(name, view, env); Ember['default'].assert("A helper named '" + name + "' could not be found", !!helper); return helper; } exports.ISNT_HELPER_CACHE = ISNT_HELPER_CACHE; }); enifed('ember-htmlbars/system/make-view-helper', ['exports'], function (exports) { 'use strict'; exports['default'] = makeViewHelper; /** @module ember @submodule ember-htmlbars */ /** Returns a helper function that renders the provided ViewClass. Used internally by Ember.Handlebars.helper and other methods involving helper/component registration. @private @method makeViewHelper @param {Function} ViewClass view class constructor @since 1.2.0 */ function makeViewHelper(ViewClass) { return { isLegacyViewHelper: true, isHTMLBars: true, viewClass: ViewClass }; } }); enifed('ember-htmlbars/system/make_bound_helper', ['exports', 'ember-htmlbars/system/helper', 'ember-metal/streams/utils'], function (exports, Helper, utils) { 'use strict'; exports['default'] = makeBoundHelper; /** @module ember @submodule ember-htmlbars */ function makeBoundHelper(fn) { return new Helper['default'](function (params, hash, templates) { Ember.assert("makeBoundHelper generated helpers do not support use with blocks", !templates.template.meta); return fn(utils.readArray(params), utils.readHash(hash)); }); } }); enifed('ember-htmlbars/system/render-view', ['exports', 'ember-htmlbars/env', 'ember-htmlbars/node-managers/view-node-manager'], function (exports, defaultEnv, view_node_manager) { 'use strict'; exports.renderHTMLBarsBlock = renderHTMLBarsBlock; function renderHTMLBarsBlock(view, block, renderNode) { var env = { lifecycleHooks: [], renderedViews: [], renderedNodes: {}, view: view, outletState: view.outletState, container: view.container, renderer: view.renderer, dom: view.renderer._dom, hooks: defaultEnv['default'].hooks, helpers: defaultEnv['default'].helpers, useFragmentCache: defaultEnv['default'].useFragmentCache }; view.env = env; view_node_manager.createOrUpdateComponent(view, {}, null, renderNode, env); var nodeManager = new view_node_manager['default'](view, null, renderNode, block, view.tagName !== ""); nodeManager.render(env, {}); } }); enifed('ember-htmlbars/templates/component', ['exports', 'ember-template-compiler/system/template'], function (exports, template) { 'use strict'; exports['default'] = template['default']((function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["content", "yield"]], locals: [], templates: [] }; })()); }); enifed('ember-htmlbars/templates/container-view', ['exports', 'ember-template-compiler/system/template'], function (exports, template) { 'use strict'; exports['default'] = template['default']((function () { var child0 = (function () { return { meta: {}, arity: 1, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["inline", "view", [["get", "childView"]], []]], locals: ["childView"], templates: [] }; })(); var child1 = (function () { var child0 = (function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["inline", "view", [["get", "view._emptyView"]], ["_defaultTagName", ["get", "view._emptyViewTagName"]]]], locals: [], templates: [] }; })(); return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "if", [["get", "view._emptyView"]], [], 0, null]], locals: [], templates: [child0] }; })(); return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "each", [["get", "view.childViews"]], ["key", "elementId"], 0, 1]], locals: [], templates: [child0, child1] }; })()); }); enifed('ember-htmlbars/templates/empty', ['exports', 'ember-template-compiler/system/template'], function (exports, template) { 'use strict'; exports['default'] = template['default']((function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); return el0; }, buildRenderNodes: function buildRenderNodes() { return []; }, statements: [], locals: [], templates: [] }; })()); }); enifed('ember-htmlbars/templates/legacy-each', ['exports', 'ember-template-compiler/system/template'], function (exports, template) { 'use strict'; exports['default'] = template['default']((function () { var child0 = (function () { var child0 = (function () { var child0 = (function () { var child0 = (function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["inline", "legacy-yield", [["get", "item"]], []]], locals: [], templates: [] }; })(); return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "view", [["get", "attrs.itemViewClass"]], ["_defaultTagName", ["get", "view._itemTagName"]], 0, null]], locals: [], templates: [child0] }; })(); var child1 = (function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["inline", "legacy-yield", [["get", "item"]], []]], locals: [], templates: [] }; })(); return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "if", [["get", "attrs.itemViewClass"]], [], 0, 1]], locals: [], templates: [child0, child1] }; })(); var child1 = (function () { var child0 = (function () { var child0 = (function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["inline", "legacy-yield", [["get", "item"]], []]], locals: [], templates: [] }; })(); return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "view", [["get", "attrs.itemViewClass"]], ["controller", ["get", "item"], "_defaultTagName", ["get", "view._itemTagName"]], 0, null]], locals: [], templates: [child0] }; })(); var child1 = (function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["inline", "legacy-yield", [["get", "item"]], ["controller", ["get", "item"]]]], locals: [], templates: [] }; })(); return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "if", [["get", "attrs.itemViewClass"]], [], 0, 1]], locals: [], templates: [child0, child1] }; })(); return { meta: {}, arity: 1, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "if", [["get", "keyword"]], [], 0, 1]], locals: ["item"], templates: [child0, child1] }; })(); var child1 = (function () { var child0 = (function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["inline", "view", [["get", "view._emptyView"]], ["_defaultTagName", ["get", "view._itemTagName"]]]], locals: [], templates: [] }; })(); return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "if", [["get", "view._emptyView"]], [], 0, null]], locals: [], templates: [child0] }; })(); return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "each", [["get", "view._arrangedContent"]], ["-legacy-keyword", ["get", "keyword"]], 0, 1]], locals: [], templates: [child0, child1] }; })()); }); enifed('ember-htmlbars/templates/link-to-escaped', ['exports', 'ember-template-compiler/system/template'], function (exports, template) { 'use strict'; exports['default'] = template['default']((function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["content", "linkTitle"]], locals: [], templates: [] }; })()); }); enifed('ember-htmlbars/templates/link-to-unescaped', ['exports', 'ember-template-compiler/system/template'], function (exports, template) { 'use strict'; exports['default'] = template['default']((function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createUnsafeMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["content", "linkTitle"]], locals: [], templates: [] }; })()); }); enifed('ember-htmlbars/templates/link-to', ['exports', 'ember-template-compiler/system/template'], function (exports, template) { 'use strict'; exports['default'] = template['default']((function () { var child0 = (function () { var child0 = (function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["content", "linkTitle"]], locals: [], templates: [] }; })(); var child1 = (function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createUnsafeMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["content", "linkTitle"]], locals: [], templates: [] }; })(); return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "if", [["get", "attrs.escaped"]], [], 0, 1]], locals: [], templates: [child0, child1] }; })(); var child1 = (function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["content", "yield"]], locals: [], templates: [] }; })(); return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "if", [["get", "linkTitle"]], [], 0, 1]], locals: [], templates: [child0, child1] }; })()); }); enifed('ember-htmlbars/templates/select-optgroup', ['exports', 'ember-template-compiler/system/template'], function (exports, template) { 'use strict'; exports['default'] = template['default']((function () { var child0 = (function () { return { meta: {}, arity: 1, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["inline", "view", [["get", "attrs.optionView"]], ["content", ["get", "item"], "selection", ["get", "attrs.selection"], "parentValue", ["get", "attrs.value"], "multiple", ["get", "attrs.multiple"], "optionLabelPath", ["get", "attrs.optionLabelPath"], "optionValuePath", ["get", "attrs.optionValuePath"]]]], locals: ["item"], templates: [] }; })(); return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "each", [["get", "attrs.content"]], [], 0, null]], locals: [], templates: [child0] }; })()); }); enifed('ember-htmlbars/templates/select-option', ['exports', 'ember-template-compiler/system/template'], function (exports, template) { 'use strict'; exports['default'] = template['default']((function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["content", "view.label"]], locals: [], templates: [] }; })()); }); enifed('ember-htmlbars/templates/select', ['exports', 'ember-template-compiler/system/template'], function (exports, template) { 'use strict'; exports['default'] = template['default']((function () { var child0 = (function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createElement("option"); dom.setAttribute(el1, "value", ""); var el2 = dom.createComment(""); dom.appendChild(el1, el2); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(dom.childAt(fragment, [0]), 0, 0); return morphs; }, statements: [["content", "view.prompt"]], locals: [], templates: [] }; })(); var child1 = (function () { var child0 = (function () { return { meta: {}, arity: 1, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["inline", "view", [["get", "view.groupView"]], ["content", ["get", "group.content"], "label", ["get", "group.label"], "selection", ["get", "view.selection"], "value", ["get", "view.value"], "multiple", ["get", "view.multiple"], "optionLabelPath", ["get", "view.optionLabelPath"], "optionValuePath", ["get", "view.optionValuePath"], "optionView", ["get", "view.optionView"]]]], locals: ["group"], templates: [] }; })(); return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "each", [["get", "view.groupedContent"]], [], 0, null]], locals: [], templates: [child0] }; })(); var child2 = (function () { var child0 = (function () { return { meta: {}, arity: 1, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["inline", "view", [["get", "view.optionView"]], ["content", ["get", "item"], "selection", ["get", "view.selection"], "parentValue", ["get", "view.value"], "multiple", ["get", "view.multiple"], "optionLabelPath", ["get", "view.optionLabelPath"], "optionValuePath", ["get", "view.optionValuePath"]]]], locals: ["item"], templates: [] }; })(); return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "each", [["get", "view.content"]], [], 0, null]], locals: [], templates: [child0] }; })(); return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); var el1 = dom.createComment(""); dom.appendChild(el0, el1); var el1 = dom.createTextNode("\n"); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(2); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); morphs[1] = dom.createMorphAt(fragment, 1, 1, contextualElement); dom.insertBoundary(fragment, 0); return morphs; }, statements: [["block", "if", [["get", "view.prompt"]], [], 0, null], ["block", "if", [["get", "view.optionGroupPath"]], [], 1, 2]], locals: [], templates: [child0, child1, child2] }; })()); }); enifed('ember-htmlbars/templates/top-level-view', ['exports', 'ember-template-compiler/system/template'], function (exports, template) { 'use strict'; exports['default'] = template['default']((function () { return { meta: {}, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["content", "outlet"]], locals: [], templates: [] }; })()); }); enifed('ember-htmlbars/utils/is-component', ['exports', 'ember-htmlbars/system/lookup-helper'], function (exports, lookup_helper) { 'use strict'; exports['default'] = isComponent; /** @module ember @submodule ember-htmlbars */ function isComponent(env, scope, path) { var container = env.container; if (!container) { return false; } if (lookup_helper.ISNT_HELPER_CACHE.get(path)) { return false; } return container._registry.has('component:' + path) || container._registry.has('template:components/' + path); } }); enifed('ember-htmlbars/utils/lookup-component', ['exports'], function (exports) { 'use strict'; exports['default'] = lookupComponent; function lookupComponent(container, tagName) { var componentLookup = container.lookup('component-lookup:main'); return { component: componentLookup.componentFor(tagName, container), layout: componentLookup.layoutFor(tagName, container) }; } }); enifed('ember-htmlbars/utils/normalize-self', ['exports'], function (exports) { 'use strict'; exports['default'] = normalizeSelf; function normalizeSelf(self) { if (self === undefined) { return null; } else { return self; } } }); enifed('ember-htmlbars/utils/string', ['exports', 'htmlbars-util', 'ember-runtime/system/string'], function (exports, htmlbars_util, EmberStringUtils) { 'use strict'; exports.htmlSafe = htmlSafe; /** @module ember @submodule ember-htmlbars */ // required so we can extend this object. function htmlSafe(str) { if (str === null || str === undefined) { return ""; } if (typeof str !== "string") { str = "" + str; } return new htmlbars_util.SafeString(str); } EmberStringUtils['default'].htmlSafe = htmlSafe; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { /** Mark a string as being safe for unescaped output with Handlebars. ```javascript '
someString
'.htmlSafe() ``` See [Ember.String.htmlSafe](/api/classes/Ember.String.html#method_htmlSafe). @method htmlSafe @for String @return {Handlebars.SafeString} a string that will not be html escaped by Handlebars */ String.prototype.htmlSafe = function () { return htmlSafe(this); }; } exports.SafeString = htmlbars_util.SafeString; exports.escapeExpression = htmlbars_util.escapeExpression; }); enifed('ember-htmlbars/utils/subscribe', ['exports', 'ember-metal/streams/utils'], function (exports, utils) { 'use strict'; exports['default'] = subscribe; function subscribe(node, env, scope, stream) { if (!utils.isStream(stream)) { return; } var component = scope.component; var unsubscribers = node.streamUnsubscribers = node.streamUnsubscribers || []; unsubscribers.push(stream.subscribe(function () { node.isDirty = true; // Whenever a render node directly inside a component becomes // dirty, we want to invoke the willRenderElement and // didRenderElement lifecycle hooks. From the perspective of the // programming model, whenever anything in the DOM changes, a // "re-render" has occured. if (component && component._renderNode) { component._renderNode.isDirty = true; } if (node.state.manager) { node.shouldReceiveAttrs = true; } node.ownerNode.emberView.scheduleRevalidate(node, utils.labelFor(stream)); })); } }); enifed('ember-htmlbars/utils/update-scope', ['exports', 'ember-metal/streams/proxy-stream', 'ember-htmlbars/utils/subscribe'], function (exports, ProxyStream, subscribe) { 'use strict'; exports['default'] = updateScope; function updateScope(scope, key, newValue, renderNode, isSelf) { var existing = scope[key]; if (existing) { existing.setSource(newValue); } else { var stream = new ProxyStream['default'](newValue, isSelf ? null : key); if (renderNode) { subscribe['default'](renderNode, scope, stream); } scope[key] = stream; } } }); enifed('ember-metal-views', ['exports', 'ember-metal-views/renderer'], function (exports, Renderer) { 'use strict'; exports.Renderer = Renderer['default']; }); enifed('ember-metal-views/renderer', ['exports', 'ember-metal/run_loop', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-views/system/build-component-template', 'ember-metal/enumerable_utils'], function (exports, run, property_get, property_set, buildComponentTemplate, enumerable_utils) { 'use strict'; function Renderer(_helper) { this._dom = _helper; } Renderer.prototype.prerenderTopLevelView = function Renderer_prerenderTopLevelView(view, renderNode) { if (view._state === "inDOM") { throw new Error("You cannot insert a View that has already been rendered"); } view.ownerView = renderNode.emberView = view; view._renderNode = renderNode; var layout = property_get.get(view, "layout"); var template = property_get.get(view, "template"); var componentInfo = { component: view, layout: layout }; var block = buildComponentTemplate['default'](componentInfo, {}, { self: view, templates: template ? { "default": template.raw } : undefined }).block; view.renderBlock(block, renderNode); view.lastResult = renderNode.lastResult; this.clearRenderedViews(view.env); }; Renderer.prototype.renderTopLevelView = function Renderer_renderTopLevelView(view, renderNode) { // Check to see if insertion has been canceled if (view._willInsert) { view._willInsert = false; this.prerenderTopLevelView(view, renderNode); this.dispatchLifecycleHooks(view.env); } }; Renderer.prototype.revalidateTopLevelView = function Renderer_revalidateTopLevelView(view) { // This guard prevents revalidation on an already-destroyed view. if (view._renderNode.lastResult) { view._renderNode.lastResult.revalidate(view.env); // supports createElement, which operates without moving the view into // the inDOM state. if (view._state === "inDOM") { this.dispatchLifecycleHooks(view.env); } this.clearRenderedViews(view.env); } }; Renderer.prototype.dispatchLifecycleHooks = function Renderer_dispatchLifecycleHooks(env) { var ownerView = env.view; var lifecycleHooks = env.lifecycleHooks; var i, hook; for (i = 0; i < lifecycleHooks.length; i++) { hook = lifecycleHooks[i]; ownerView._dispatching = hook.type; switch (hook.type) { case "didInsertElement": this.didInsertElement(hook.view);break; case "didUpdate": this.didUpdate(hook.view);break; } this.didRender(hook.view); } ownerView._dispatching = null; env.lifecycleHooks.length = 0; }; Renderer.prototype.ensureViewNotRendering = function Renderer_ensureViewNotRendering(view) { var env = view.ownerView.env; if (env && enumerable_utils.indexOf(env.renderedViews, view.elementId) !== -1) { throw new Error("Something you did caused a view to re-render after it rendered but before it was inserted into the DOM."); } }; Renderer.prototype.clearRenderedViews = function Renderer_clearRenderedViews(env) { env.renderedNodes = {}; env.renderedViews.length = 0; }; // This entry point is called from top-level `view.appendTo` Renderer.prototype.appendTo = function Renderer_appendTo(view, target) { var morph = this._dom.appendMorph(target); morph.ownerNode = morph; view._willInsert = true; run['default'].schedule("render", this, this.renderTopLevelView, view, morph); }; Renderer.prototype.replaceIn = function Renderer_replaceIn(view, target) { var morph = this._dom.replaceContentWithMorph(target); morph.ownerNode = morph; view._willInsert = true; run['default'].scheduleOnce("render", this, this.renderTopLevelView, view, morph); }; Renderer.prototype.createElement = function Renderer_createElement(view) { var morph = this._dom.createFragmentMorph(); morph.ownerNode = morph; this.prerenderTopLevelView(view, morph); }; // inBuffer Renderer.prototype.willCreateElement = function () {}; Renderer.prototype.didCreateElement = function (view, element) { if (element) { view.element = element; } if (view._transitionTo) { view._transitionTo("hasElement"); } }; // hasElement Renderer.prototype.willInsertElement = function (view) { if (view.trigger) { view.trigger("willInsertElement"); } }; // will place into DOM Renderer.prototype.setAttrs = function (view, attrs) { property_set.set(view, "attrs", attrs); }; // set attrs the first time Renderer.prototype.componentInitAttrs = function (component, attrs) { property_set.set(component, "attrs", attrs); component.trigger("didInitAttrs", { attrs: attrs }); component.trigger("didReceiveAttrs", { newAttrs: attrs }); }; // set attrs the first time Renderer.prototype.didInsertElement = function (view) { if (view._transitionTo) { view._transitionTo("inDOM"); } if (view.trigger) { view.trigger("didInsertElement"); } }; // inDOM // placed into DOM Renderer.prototype.didUpdate = function (view) { if (view.trigger) { view.trigger("didUpdate"); } }; Renderer.prototype.didRender = function (view) { if (view.trigger) { view.trigger("didRender"); } }; Renderer.prototype.updateAttrs = function (view, attrs) { if (view.willReceiveAttrs) { view.willReceiveAttrs(attrs); } this.setAttrs(view, attrs); }; // setting new attrs Renderer.prototype.componentUpdateAttrs = function (component, oldAttrs, newAttrs) { property_set.set(component, "attrs", newAttrs); component.trigger("didUpdateAttrs", { oldAttrs: oldAttrs, newAttrs: newAttrs }); component.trigger("didReceiveAttrs", { oldAttrs: oldAttrs, newAttrs: newAttrs }); }; Renderer.prototype.willUpdate = function (view, attrs) { if (view.willUpdate) { view.willUpdate(attrs); } }; Renderer.prototype.componentWillUpdate = function (component) { component.trigger("willUpdate"); }; Renderer.prototype.willRender = function (view) { if (view.willRender) { view.willRender(); } }; Renderer.prototype.componentWillRender = function (component) { component.trigger("willRender"); }; Renderer.prototype.remove = function (view, shouldDestroy) { this.willDestroyElement(view); view._willRemoveElement = true; run['default'].schedule("render", this, this.renderElementRemoval, view); }; Renderer.prototype.renderElementRemoval = function Renderer_renderElementRemoval(view) { // Use the _willRemoveElement flag to avoid mulitple removal attempts in // case many have been scheduled. This should be more performant than using // `scheduleOnce`. if (view._willRemoveElement) { view._willRemoveElement = false; if (view._renderNode) { view._renderNode.clear(); } this.didDestroyElement(view); } }; Renderer.prototype.willRemoveElement = function () {}; Renderer.prototype.willDestroyElement = function (view) { if (view._willDestroyElement) { view._willDestroyElement(); } if (view.trigger) { view.trigger("willDestroyElement"); view.trigger("willClearRender"); } view._transitionTo("destroying", false); var childViews = view.childViews; if (childViews) { for (var i = 0; i < childViews.length; i++) { this.willDestroyElement(childViews[i]); } } }; Renderer.prototype.didDestroyElement = function (view) { view.element = null; // Views that are being destroyed should never go back to the preRender state. // However if we're just destroying an element on a view (as is the case when // using View#remove) then the view should go to a preRender state so that // it can be rendered again later. if (view._state !== "destroying") { view._transitionTo("preRender"); } var childViews = view.childViews; if (childViews) { for (var i = 0; i < childViews.length; i++) { this.didDestroyElement(childViews[i]); } } }; // element destroyed so view.destroy shouldn't try to remove it removedFromDOM exports['default'] = Renderer; /*view*/ /*view*/ }); enifed('ember-metal', ['exports', 'ember-metal/core', 'ember-metal/merge', 'ember-metal/instrumentation', 'ember-metal/utils', 'ember-metal/error', 'ember-metal/enumerable_utils', 'ember-metal/cache', 'ember-metal/platform/define_property', 'ember-metal/platform/create', 'ember-metal/array', 'ember-metal/logger', 'ember-metal/property_get', 'ember-metal/events', 'ember-metal/observer_set', 'ember-metal/property_events', 'ember-metal/properties', 'ember-metal/property_set', 'ember-metal/map', 'ember-metal/get_properties', 'ember-metal/set_properties', 'ember-metal/watch_key', 'ember-metal/chains', 'ember-metal/watch_path', 'ember-metal/watching', 'ember-metal/expand_properties', 'ember-metal/computed', 'ember-metal/alias', 'ember-metal/computed_macros', 'ember-metal/observer', 'ember-metal/mixin', 'ember-metal/binding', 'ember-metal/run_loop', 'ember-metal/libraries', 'ember-metal/is_none', 'ember-metal/is_empty', 'ember-metal/is_blank', 'ember-metal/is_present', 'ember-metal/keys', 'backburner', 'ember-metal/streams/utils', 'ember-metal/streams/stream'], function (exports, Ember, merge, instrumentation, utils, EmberError, EnumerableUtils, Cache, define_property, create, array, Logger, property_get, events, ObserverSet, property_events, properties, property_set, map, getProperties, setProperties, watch_key, chains, watch_path, watching, expandProperties, computed, alias, computed_macros, observer, mixin, binding, run, Libraries, isNone, isEmpty, isBlank, isPresent, keys, Backburner, streams__utils, Stream) { 'use strict'; /** Ember Metal @module ember @submodule ember-metal */ // BEGIN IMPORTS computed.computed.empty = computed_macros.empty; computed.computed.notEmpty = computed_macros.notEmpty; computed.computed.none = computed_macros.none; computed.computed.not = computed_macros.not; computed.computed.bool = computed_macros.bool; computed.computed.match = computed_macros.match; computed.computed.equal = computed_macros.equal; computed.computed.gt = computed_macros.gt; computed.computed.gte = computed_macros.gte; computed.computed.lt = computed_macros.lt; computed.computed.lte = computed_macros.lte; computed.computed.alias = alias['default']; computed.computed.oneWay = computed_macros.oneWay; computed.computed.reads = computed_macros.oneWay; computed.computed.readOnly = computed_macros.readOnly; computed.computed.defaultTo = computed_macros.defaultTo; computed.computed.deprecatingAlias = computed_macros.deprecatingAlias; computed.computed.and = computed_macros.and; computed.computed.or = computed_macros.or; computed.computed.any = computed_macros.any; computed.computed.collect = computed_macros.collect; // END IMPORTS // BEGIN EXPORTS var EmberInstrumentation = Ember['default'].Instrumentation = {}; EmberInstrumentation.instrument = instrumentation.instrument; EmberInstrumentation.subscribe = instrumentation.subscribe; EmberInstrumentation.unsubscribe = instrumentation.unsubscribe; EmberInstrumentation.reset = instrumentation.reset; Ember['default'].instrument = instrumentation.instrument; Ember['default'].subscribe = instrumentation.subscribe; Ember['default']._Cache = Cache['default']; Ember['default'].generateGuid = utils.generateGuid; Ember['default'].GUID_KEY = utils.GUID_KEY; Ember['default'].create = create['default']; Ember['default'].keys = keys['default']; Ember['default'].platform = { defineProperty: properties.defineProperty, hasPropertyAccessors: define_property.hasPropertyAccessors }; var EmberArrayPolyfills = Ember['default'].ArrayPolyfills = {}; EmberArrayPolyfills.map = array.map; EmberArrayPolyfills.forEach = array.forEach; EmberArrayPolyfills.filter = array.filter; EmberArrayPolyfills.indexOf = array.indexOf; Ember['default'].Error = EmberError['default']; Ember['default'].guidFor = utils.guidFor; Ember['default'].META_DESC = utils.META_DESC; Ember['default'].EMPTY_META = utils.EMPTY_META; Ember['default'].meta = utils.meta; Ember['default'].getMeta = utils.getMeta; Ember['default'].setMeta = utils.setMeta; Ember['default'].metaPath = utils.metaPath; Ember['default'].inspect = utils.inspect; Ember['default'].tryCatchFinally = utils.deprecatedTryCatchFinally; Ember['default'].makeArray = utils.makeArray; Ember['default'].canInvoke = utils.canInvoke; Ember['default'].tryInvoke = utils.tryInvoke; Ember['default'].tryFinally = utils.deprecatedTryFinally; Ember['default'].wrap = utils.wrap; Ember['default'].apply = utils.apply; Ember['default'].applyStr = utils.applyStr; Ember['default'].uuid = utils.uuid; Ember['default'].Logger = Logger['default']; Ember['default'].get = property_get.get; Ember['default'].getWithDefault = property_get.getWithDefault; Ember['default'].normalizeTuple = property_get.normalizeTuple; Ember['default']._getPath = property_get._getPath; Ember['default'].EnumerableUtils = EnumerableUtils['default']; Ember['default'].on = events.on; Ember['default'].addListener = events.addListener; Ember['default'].removeListener = events.removeListener; Ember['default']._suspendListener = events.suspendListener; Ember['default']._suspendListeners = events.suspendListeners; Ember['default'].sendEvent = events.sendEvent; Ember['default'].hasListeners = events.hasListeners; Ember['default'].watchedEvents = events.watchedEvents; Ember['default'].listenersFor = events.listenersFor; Ember['default'].accumulateListeners = events.accumulateListeners; Ember['default']._ObserverSet = ObserverSet['default']; Ember['default'].propertyWillChange = property_events.propertyWillChange; Ember['default'].propertyDidChange = property_events.propertyDidChange; Ember['default'].overrideChains = property_events.overrideChains; Ember['default'].beginPropertyChanges = property_events.beginPropertyChanges; Ember['default'].endPropertyChanges = property_events.endPropertyChanges; Ember['default'].changeProperties = property_events.changeProperties; Ember['default'].defineProperty = properties.defineProperty; Ember['default'].set = property_set.set; Ember['default'].trySet = property_set.trySet; Ember['default'].OrderedSet = map.OrderedSet; Ember['default'].Map = map.Map; Ember['default'].MapWithDefault = map.MapWithDefault; Ember['default'].getProperties = getProperties['default']; Ember['default'].setProperties = setProperties['default']; Ember['default'].watchKey = watch_key.watchKey; Ember['default'].unwatchKey = watch_key.unwatchKey; Ember['default'].flushPendingChains = chains.flushPendingChains; Ember['default'].removeChainWatcher = chains.removeChainWatcher; Ember['default']._ChainNode = chains.ChainNode; Ember['default'].finishChains = chains.finishChains; Ember['default'].watchPath = watch_path.watchPath; Ember['default'].unwatchPath = watch_path.unwatchPath; Ember['default'].watch = watching.watch; Ember['default'].isWatching = watching.isWatching; Ember['default'].unwatch = watching.unwatch; Ember['default'].rewatch = watching.rewatch; Ember['default'].destroy = watching.destroy; Ember['default'].expandProperties = expandProperties['default']; Ember['default'].ComputedProperty = computed.ComputedProperty; Ember['default'].computed = computed.computed; Ember['default'].cacheFor = computed.cacheFor; Ember['default'].addObserver = observer.addObserver; Ember['default'].observersFor = observer.observersFor; Ember['default'].removeObserver = observer.removeObserver; Ember['default'].addBeforeObserver = observer.addBeforeObserver; Ember['default']._suspendBeforeObserver = observer._suspendBeforeObserver; Ember['default']._suspendBeforeObservers = observer._suspendBeforeObservers; Ember['default']._suspendObserver = observer._suspendObserver; Ember['default']._suspendObservers = observer._suspendObservers; Ember['default'].beforeObserversFor = observer.beforeObserversFor; Ember['default'].removeBeforeObserver = observer.removeBeforeObserver; Ember['default'].IS_BINDING = mixin.IS_BINDING; Ember['default'].required = mixin.required; Ember['default'].aliasMethod = mixin.aliasMethod; Ember['default'].observer = mixin.observer; Ember['default'].immediateObserver = mixin.immediateObserver; Ember['default'].beforeObserver = mixin.beforeObserver; Ember['default'].mixin = mixin.mixin; Ember['default'].Mixin = mixin.Mixin; Ember['default'].oneWay = binding.oneWay; Ember['default'].bind = binding.bind; Ember['default'].Binding = binding.Binding; Ember['default'].isGlobalPath = binding.isGlobalPath; Ember['default'].run = run['default']; /** * @class Backburner * @for Ember * @private */ Ember['default'].Backburner = Backburner['default']; Ember['default'].libraries = new Libraries['default'](); Ember['default'].libraries.registerCoreLibrary("Ember", Ember['default'].VERSION); Ember['default'].isNone = isNone['default']; Ember['default'].isEmpty = isEmpty['default']; Ember['default'].isBlank = isBlank['default']; Ember['default'].isPresent = isPresent['default']; Ember['default'].merge = merge['default']; /** A function may be assigned to `Ember.onerror` to be called when Ember internals encounter an error. This is useful for specialized error handling and reporting code. ```javascript Ember.onerror = function(error) { Em.$.ajax('/report-error', 'POST', { stack: error.stack, otherInformation: 'whatever app state you want to provide' }); }; ``` Internally, `Ember.onerror` is used as Backburner's error handler. @event onerror @for Ember @param {Exception} error the error object */ Ember['default'].onerror = null; // END EXPORTS // do this for side-effects of updating Ember.assert, warn, etc when // ember-debug is present if (Ember['default'].__loader.registry["ember-debug"]) { requireModule("ember-debug"); } exports['default'] = Ember['default']; }); enifed('ember-metal/alias', ['exports', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/core', 'ember-metal/error', 'ember-metal/properties', 'ember-metal/computed', 'ember-metal/platform/create', 'ember-metal/utils', 'ember-metal/dependent_keys'], function (exports, property_get, property_set, Ember, EmberError, properties, computed, create, utils, dependent_keys) { 'use strict'; exports.AliasedProperty = AliasedProperty; exports['default'] = alias; function alias(altKey) { return new AliasedProperty(altKey); } function AliasedProperty(altKey) { this.isDescriptor = true; this.altKey = altKey; this._dependentKeys = [altKey]; } AliasedProperty.prototype = create['default'](properties.Descriptor.prototype); AliasedProperty.prototype.get = function AliasedProperty_get(obj, keyName) { return property_get.get(obj, this.altKey); }; AliasedProperty.prototype.set = function AliasedProperty_set(obj, keyName, value) { return property_set.set(obj, this.altKey, value); }; AliasedProperty.prototype.willWatch = function (obj, keyName) { dependent_keys.addDependentKeys(this, obj, keyName, utils.meta(obj)); }; AliasedProperty.prototype.didUnwatch = function (obj, keyName) { dependent_keys.removeDependentKeys(this, obj, keyName, utils.meta(obj)); }; AliasedProperty.prototype.setup = function (obj, keyName) { Ember['default'].assert("Setting alias '" + keyName + "' on self", this.altKey !== keyName); var m = utils.meta(obj); if (m.watching[keyName]) { dependent_keys.addDependentKeys(this, obj, keyName, m); } }; AliasedProperty.prototype.teardown = function (obj, keyName) { var m = utils.meta(obj); if (m.watching[keyName]) { dependent_keys.removeDependentKeys(this, obj, keyName, m); } }; AliasedProperty.prototype.readOnly = function () { this.set = AliasedProperty_readOnlySet; return this; }; function AliasedProperty_readOnlySet(obj, keyName, value) { throw new EmberError['default']("Cannot set read-only property '" + keyName + "' on object: " + utils.inspect(obj)); } AliasedProperty.prototype.oneWay = function () { this.set = AliasedProperty_oneWaySet; return this; }; function AliasedProperty_oneWaySet(obj, keyName, value) { properties.defineProperty(obj, keyName, null); return property_set.set(obj, keyName, value); } // Backwards compatibility with Ember Data AliasedProperty.prototype._meta = undefined; AliasedProperty.prototype.meta = computed.ComputedProperty.prototype.meta; }); enifed('ember-metal/array', ['exports'], function (exports) { 'use strict'; /** @module ember-metal */ var ArrayPrototype = Array.prototype; // Testing this is not ideal, but we want to use native functions // if available, but not to use versions created by libraries like Prototype var isNativeFunc = function (func) { // This should probably work in all browsers likely to have ES5 array methods return func && Function.prototype.toString.call(func).indexOf("[native code]") > -1; }; var defineNativeShim = function (nativeFunc, shim) { if (isNativeFunc(nativeFunc)) { return nativeFunc; } return shim; }; // From: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/map var map = defineNativeShim(ArrayPrototype.map, function (fun) { //"use strict"; if (this === void 0 || this === null || typeof fun !== "function") { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; var res = new Array(len); for (var i = 0; i < len; i++) { if (i in t) { res[i] = fun.call(arguments[1], t[i], i, t); } } return res; }); // From: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/foreach var forEach = defineNativeShim(ArrayPrototype.forEach, function (fun) { //"use strict"; if (this === void 0 || this === null || typeof fun !== "function") { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; for (var i = 0; i < len; i++) { if (i in t) { fun.call(arguments[1], t[i], i, t); } } }); var indexOf = defineNativeShim(ArrayPrototype.indexOf, function (obj, fromIndex) { if (fromIndex === null || fromIndex === undefined) { fromIndex = 0; } else if (fromIndex < 0) { fromIndex = Math.max(0, this.length + fromIndex); } for (var i = fromIndex, j = this.length; i < j; i++) { if (this[i] === obj) { return i; } } return -1; }); var lastIndexOf = defineNativeShim(ArrayPrototype.lastIndexOf, function (obj, fromIndex) { var len = this.length; var idx; if (fromIndex === undefined) { fromIndex = len - 1; } else { fromIndex = fromIndex < 0 ? Math.ceil(fromIndex) : Math.floor(fromIndex); } if (fromIndex < 0) { fromIndex += len; } for (idx = fromIndex; idx >= 0; idx--) { if (this[idx] === obj) { return idx; } } return -1; }); var filter = defineNativeShim(ArrayPrototype.filter, function (fn, context) { var i, value; var result = []; var length = this.length; for (i = 0; i < length; i++) { if (this.hasOwnProperty(i)) { value = this[i]; if (fn.call(context, value, i, this)) { result.push(value); } } } return result; }); if (Ember.SHIM_ES5) { ArrayPrototype.map = ArrayPrototype.map || map; ArrayPrototype.forEach = ArrayPrototype.forEach || forEach; ArrayPrototype.filter = ArrayPrototype.filter || filter; ArrayPrototype.indexOf = ArrayPrototype.indexOf || indexOf; ArrayPrototype.lastIndexOf = ArrayPrototype.lastIndexOf || lastIndexOf; } /** Array polyfills to support ES5 features in older browsers. @namespace Ember @property ArrayPolyfills */ exports.map = map; exports.forEach = forEach; exports.filter = filter; exports.indexOf = indexOf; exports.lastIndexOf = lastIndexOf; }); enifed('ember-metal/binding', ['exports', 'ember-metal/core', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/utils', 'ember-metal/observer', 'ember-metal/run_loop', 'ember-metal/path_cache'], function (exports, Ember, property_get, property_set, utils, observer, run, path_cache) { 'use strict'; exports.bind = bind; exports.oneWay = oneWay; exports.Binding = Binding; Ember['default'].LOG_BINDINGS = false || !!Ember['default'].ENV.LOG_BINDINGS; /** Returns true if the provided path is global (e.g., `MyApp.fooController.bar`) instead of local (`foo.bar.baz`). @method isGlobalPath @for Ember @private @param {String} path @return Boolean */ function getWithGlobals(obj, path) { return property_get.get(path_cache.isGlobal(path) ? Ember['default'].lookup : obj, path); } // .......................................................... // BINDING // function Binding(toPath, fromPath) { this._direction = undefined; this._from = fromPath; this._to = toPath; this._readyToSync = undefined; this._oneWay = undefined; } /** @class Binding @namespace Ember */ Binding.prototype = { /** This copies the Binding so it can be connected to another object. @method copy @return {Ember.Binding} `this` */ copy: function () { var copy = new Binding(this._to, this._from); if (this._oneWay) { copy._oneWay = true; } return copy; }, // .......................................................... // CONFIG // /** This will set `from` property path to the specified value. It will not attempt to resolve this property path to an actual object until you connect the binding. The binding will search for the property path starting at the root object you pass when you `connect()` the binding. It follows the same rules as `get()` - see that method for more information. @method from @param {String} path the property path to connect to @return {Ember.Binding} `this` */ from: function (path) { this._from = path; return this; }, /** This will set the `to` property path to the specified value. It will not attempt to resolve this property path to an actual object until you connect the binding. The binding will search for the property path starting at the root object you pass when you `connect()` the binding. It follows the same rules as `get()` - see that method for more information. @method to @param {String|Tuple} path A property path or tuple @return {Ember.Binding} `this` */ to: function (path) { this._to = path; return this; }, /** Configures the binding as one way. A one-way binding will relay changes on the `from` side to the `to` side, but not the other way around. This means that if you change the `to` side directly, the `from` side may have a different value. @method oneWay @return {Ember.Binding} `this` */ oneWay: function () { this._oneWay = true; return this; }, /** @method toString @return {String} string representation of binding */ toString: function () { var oneWay = this._oneWay ? "[oneWay]" : ""; return "Ember.Binding<" + utils.guidFor(this) + ">(" + this._from + " -> " + this._to + ")" + oneWay; }, // .......................................................... // CONNECT AND SYNC // /** Attempts to connect this binding instance so that it can receive and relay changes. This method will raise an exception if you have not set the from/to properties yet. @method connect @param {Object} obj The root object for this binding. @return {Ember.Binding} `this` */ connect: function (obj) { Ember['default'].assert("Must pass a valid object to Ember.Binding.connect()", !!obj); var fromPath = this._from; var toPath = this._to; property_set.trySet(obj, toPath, getWithGlobals(obj, fromPath)); // add an observer on the object to be notified when the binding should be updated observer.addObserver(obj, fromPath, this, this.fromDidChange); // if the binding is a two-way binding, also set up an observer on the target if (!this._oneWay) { observer.addObserver(obj, toPath, this, this.toDidChange); } this._readyToSync = true; return this; }, /** Disconnects the binding instance. Changes will no longer be relayed. You will not usually need to call this method. @method disconnect @param {Object} obj The root object you passed when connecting the binding. @return {Ember.Binding} `this` */ disconnect: function (obj) { Ember['default'].assert("Must pass a valid object to Ember.Binding.disconnect()", !!obj); var twoWay = !this._oneWay; // remove an observer on the object so we're no longer notified of // changes that should update bindings. observer.removeObserver(obj, this._from, this, this.fromDidChange); // if the binding is two-way, remove the observer from the target as well if (twoWay) { observer.removeObserver(obj, this._to, this, this.toDidChange); } this._readyToSync = false; // disable scheduled syncs... return this; }, // .......................................................... // PRIVATE // /* called when the from side changes */ fromDidChange: function (target) { this._scheduleSync(target, "fwd"); }, /* called when the to side changes */ toDidChange: function (target) { this._scheduleSync(target, "back"); }, _scheduleSync: function (obj, dir) { var existingDir = this._direction; // if we haven't scheduled the binding yet, schedule it if (existingDir === undefined) { run['default'].schedule("sync", this, this._sync, obj); this._direction = dir; } // If both a 'back' and 'fwd' sync have been scheduled on the same object, // default to a 'fwd' sync so that it remains deterministic. if (existingDir === "back" && dir === "fwd") { this._direction = "fwd"; } }, _sync: function (obj) { var log = Ember['default'].LOG_BINDINGS; // don't synchronize destroyed objects or disconnected bindings if (obj.isDestroyed || !this._readyToSync) { return; } // get the direction of the binding for the object we are // synchronizing from var direction = this._direction; var fromPath = this._from; var toPath = this._to; this._direction = undefined; // if we're synchronizing from the remote object... if (direction === "fwd") { var fromValue = getWithGlobals(obj, this._from); if (log) { Ember['default'].Logger.log(" ", this.toString(), "->", fromValue, obj); } if (this._oneWay) { property_set.trySet(obj, toPath, fromValue); } else { observer._suspendObserver(obj, toPath, this, this.toDidChange, function () { property_set.trySet(obj, toPath, fromValue); }); } // if we're synchronizing *to* the remote object } else if (direction === "back") { var toValue = property_get.get(obj, this._to); if (log) { Ember['default'].Logger.log(" ", this.toString(), "<-", toValue, obj); } observer._suspendObserver(obj, fromPath, this, this.fromDidChange, function () { property_set.trySet(path_cache.isGlobal(fromPath) ? Ember['default'].lookup : obj, fromPath, toValue); }); } } }; function mixinProperties(to, from) { for (var key in from) { if (from.hasOwnProperty(key)) { to[key] = from[key]; } } } mixinProperties(Binding, { /* See `Ember.Binding.from`. @method from @static */ from: function (from) { var C = this; return new C(undefined, from); }, /* See `Ember.Binding.to`. @method to @static */ to: function (to) { var C = this; return new C(to, undefined); }, /** Creates a new Binding instance and makes it apply in a single direction. A one-way binding will relay changes on the `from` side object (supplied as the `from` argument) the `to` side, but not the other way around. This means that if you change the "to" side directly, the "from" side may have a different value. See `Binding.oneWay`. @method oneWay @param {String} from from path. @param {Boolean} [flag] (Optional) passing nothing here will make the binding `oneWay`. You can instead pass `false` to disable `oneWay`, making the binding two way again. @return {Ember.Binding} `this` */ oneWay: function (from, flag) { var C = this; return new C(undefined, from).oneWay(flag); } }); /** An `Ember.Binding` connects the properties of two objects so that whenever the value of one property changes, the other property will be changed also. ## Automatic Creation of Bindings with `/^*Binding/`-named Properties You do not usually create Binding objects directly but instead describe bindings in your class or object definition using automatic binding detection. Properties ending in a `Binding` suffix will be converted to `Ember.Binding` instances. The value of this property should be a string representing a path to another object or a custom binding instance created using Binding helpers (see "One Way Bindings"): ``` valueBinding: "MyApp.someController.title" ``` This will create a binding from `MyApp.someController.title` to the `value` property of your object instance automatically. Now the two values will be kept in sync. ## One Way Bindings One especially useful binding customization you can use is the `oneWay()` helper. This helper tells Ember that you are only interested in receiving changes on the object you are binding from. For example, if you are binding to a preference and you want to be notified if the preference has changed, but your object will not be changing the preference itself, you could do: ``` bigTitlesBinding: Ember.Binding.oneWay("MyApp.preferencesController.bigTitles") ``` This way if the value of `MyApp.preferencesController.bigTitles` changes the `bigTitles` property of your object will change also. However, if you change the value of your `bigTitles` property, it will not update the `preferencesController`. One way bindings are almost twice as fast to setup and twice as fast to execute because the binding only has to worry about changes to one side. You should consider using one way bindings anytime you have an object that may be created frequently and you do not intend to change a property; only to monitor it for changes (such as in the example above). ## Adding Bindings Manually All of the examples above show you how to configure a custom binding, but the result of these customizations will be a binding template, not a fully active Binding instance. The binding will actually become active only when you instantiate the object the binding belongs to. It is useful however, to understand what actually happens when the binding is activated. For a binding to function it must have at least a `from` property and a `to` property. The `from` property path points to the object/key that you want to bind from while the `to` path points to the object/key you want to bind to. When you define a custom binding, you are usually describing the property you want to bind from (such as `MyApp.someController.value` in the examples above). When your object is created, it will automatically assign the value you want to bind `to` based on the name of your binding key. In the examples above, during init, Ember objects will effectively call something like this on your binding: ```javascript binding = Ember.Binding.from("valueBinding").to("value"); ``` This creates a new binding instance based on the template you provide, and sets the to path to the `value` property of the new object. Now that the binding is fully configured with a `from` and a `to`, it simply needs to be connected to become active. This is done through the `connect()` method: ```javascript binding.connect(this); ``` Note that when you connect a binding you pass the object you want it to be connected to. This object will be used as the root for both the from and to side of the binding when inspecting relative paths. This allows the binding to be automatically inherited by subclassed objects as well. This also allows you to bind between objects using the paths you declare in `from` and `to`: ```javascript // Example 1 binding = Ember.Binding.from("App.someObject.value").to("value"); binding.connect(this); // Example 2 binding = Ember.Binding.from("parentView.value").to("App.someObject.value"); binding.connect(this); ``` Now that the binding is connected, it will observe both the from and to side and relay changes. If you ever needed to do so (you almost never will, but it is useful to understand this anyway), you could manually create an active binding by using the `Ember.bind()` helper method. (This is the same method used by to setup your bindings on objects): ```javascript Ember.bind(MyApp.anotherObject, "value", "MyApp.someController.value"); ``` Both of these code fragments have the same effect as doing the most friendly form of binding creation like so: ```javascript MyApp.anotherObject = Ember.Object.create({ valueBinding: "MyApp.someController.value", // OTHER CODE FOR THIS OBJECT... }); ``` Ember's built in binding creation method makes it easy to automatically create bindings for you. You should always use the highest-level APIs available, even if you understand how it works underneath. @class Binding @namespace Ember @since Ember 0.9 */ // Ember.Binding = Binding; ES6TODO: where to put this? /** Global helper method to create a new binding. Just pass the root object along with a `to` and `from` path to create and connect the binding. @method bind @for Ember @param {Object} obj The root object of the transform. @param {String} to The path to the 'to' side of the binding. Must be relative to obj. @param {String} from The path to the 'from' side of the binding. Must be relative to obj or a global path. @return {Ember.Binding} binding instance */ function bind(obj, to, from) { return new Binding(to, from).connect(obj); } /** @method oneWay @for Ember @param {Object} obj The root object of the transform. @param {String} to The path to the 'to' side of the binding. Must be relative to obj. @param {String} from The path to the 'from' side of the binding. Must be relative to obj or a global path. @return {Ember.Binding} binding instance */ function oneWay(obj, to, from) { return new Binding(to, from).oneWay().connect(obj); } exports.isGlobalPath = path_cache.isGlobal; }); enifed('ember-metal/cache', ['exports', 'ember-metal/dictionary'], function (exports, dictionary) { 'use strict'; exports['default'] = Cache; function Cache(limit, func) { this.store = dictionary['default'](null); this.size = 0; this.misses = 0; this.hits = 0; this.limit = limit; this.func = func; } var UNDEFINED = function () {}; Cache.prototype = { set: function (key, value) { if (this.limit > this.size) { this.size++; if (value === undefined) { this.store[key] = UNDEFINED; } else { this.store[key] = value; } } return value; }, get: function (key) { var value = this.store[key]; if (value === undefined) { this.misses++; value = this.set(key, this.func(key)); } else if (value === UNDEFINED) { this.hits++; value = undefined; } else { this.hits++; // nothing to translate } return value; }, purge: function () { this.store = dictionary['default'](null); this.size = 0; this.hits = 0; this.misses = 0; } }; }); enifed('ember-metal/chains', ['exports', 'ember-metal/core', 'ember-metal/property_get', 'ember-metal/utils', 'ember-metal/array', 'ember-metal/watch_key'], function (exports, Ember, property_get, utils, array, watch_key) { 'use strict'; exports.flushPendingChains = flushPendingChains; exports.finishChains = finishChains; exports.removeChainWatcher = removeChainWatcher; exports.ChainNode = ChainNode; var warn = Ember['default'].warn; var FIRST_KEY = /^([^\.]+)/; function firstKey(path) { return path.match(FIRST_KEY)[0]; } function isObject(obj) { return obj && typeof obj === "object"; } var pendingQueue = []; // attempts to add the pendingQueue chains again. If some of them end up // back in the queue and reschedule is true, schedules a timeout to try // again. function flushPendingChains() { if (pendingQueue.length === 0) { return; } var queue = pendingQueue; pendingQueue = []; array.forEach.call(queue, function (q) { q[0].add(q[1]); }); warn("Watching an undefined global, Ember expects watched globals to be" + " setup by the time the run loop is flushed, check for typos", pendingQueue.length === 0); } function addChainWatcher(obj, keyName, node) { if (!isObject(obj)) { return; } var m = utils.meta(obj); var nodes = m.chainWatchers; if (!m.hasOwnProperty("chainWatchers")) { // FIXME?! nodes = m.chainWatchers = {}; } if (!nodes[keyName]) { nodes[keyName] = []; } nodes[keyName].push(node); watch_key.watchKey(obj, keyName, m); } function removeChainWatcher(obj, keyName, node) { if (!isObject(obj)) { return; } var m = obj["__ember_meta__"]; if (m && !m.hasOwnProperty("chainWatchers")) { return; } // nothing to do var nodes = m && m.chainWatchers; if (nodes && nodes[keyName]) { nodes = nodes[keyName]; for (var i = 0, l = nodes.length; i < l; i++) { if (nodes[i] === node) { nodes.splice(i, 1); break; } } } watch_key.unwatchKey(obj, keyName, m); } // A ChainNode watches a single key on an object. If you provide a starting // value for the key then the node won't actually watch it. For a root node // pass null for parent and key and object for value. function ChainNode(parent, key, value) { this._parent = parent; this._key = key; // _watching is true when calling get(this._parent, this._key) will // return the value of this node. // // It is false for the root of a chain (because we have no parent) // and for global paths (because the parent node is the object with // the observer on it) this._watching = value === undefined; this._value = value; this._paths = {}; if (this._watching) { this._object = parent.value(); if (this._object) { addChainWatcher(this._object, this._key, this); } } // Special-case: the EachProxy relies on immediate evaluation to // establish its observers. // // TODO: Replace this with an efficient callback that the EachProxy // can implement. if (this._parent && this._parent._key === "@each") { this.value(); } } function lazyGet(obj, key) { if (!obj) { return; } var meta = obj["__ember_meta__"]; // check if object meant only to be a prototype if (meta && meta.proto === obj) { return; } if (key === "@each") { return property_get.get(obj, key); } // if a CP only return cached value var possibleDesc = obj[key]; var desc = possibleDesc !== null && typeof possibleDesc === "object" && possibleDesc.isDescriptor ? possibleDesc : undefined; if (desc && desc._cacheable) { if (meta.cache && key in meta.cache) { return meta.cache[key]; } else { return; } } return property_get.get(obj, key); } ChainNode.prototype = { value: function () { if (this._value === undefined && this._watching) { var obj = this._parent.value(); this._value = lazyGet(obj, this._key); } return this._value; }, destroy: function () { if (this._watching) { var obj = this._object; if (obj) { removeChainWatcher(obj, this._key, this); } this._watching = false; // so future calls do nothing } }, // copies a top level object only copy: function (obj) { var ret = new ChainNode(null, null, obj); var paths = this._paths; var path; for (path in paths) { // this check will also catch non-number vals. if (paths[path] <= 0) { continue; } ret.add(path); } return ret; }, // called on the root node of a chain to setup watchers on the specified // path. add: function (path) { var obj, tuple, key, src, paths; paths = this._paths; paths[path] = (paths[path] || 0) + 1; obj = this.value(); tuple = property_get.normalizeTuple(obj, path); // the path was a local path if (tuple[0] && tuple[0] === obj) { path = tuple[1]; key = firstKey(path); path = path.slice(key.length + 1); // global path, but object does not exist yet. // put into a queue and try to connect later. } else if (!tuple[0]) { pendingQueue.push([this, path]); tuple.length = 0; return; // global path, and object already exists } else { src = tuple[0]; key = path.slice(0, 0 - (tuple[1].length + 1)); path = tuple[1]; } tuple.length = 0; this.chain(key, path, src); }, // called on the root node of a chain to teardown watcher on the specified // path remove: function (path) { var obj, tuple, key, src, paths; paths = this._paths; if (paths[path] > 0) { paths[path]--; } obj = this.value(); tuple = property_get.normalizeTuple(obj, path); if (tuple[0] === obj) { path = tuple[1]; key = firstKey(path); path = path.slice(key.length + 1); } else { src = tuple[0]; key = path.slice(0, 0 - (tuple[1].length + 1)); path = tuple[1]; } tuple.length = 0; this.unchain(key, path); }, count: 0, chain: function (key, path, src) { var chains = this._chains; var node; if (!chains) { chains = this._chains = {}; } node = chains[key]; if (!node) { node = chains[key] = new ChainNode(this, key, src); } node.count++; // count chains... // chain rest of path if there is one if (path) { key = firstKey(path); path = path.slice(key.length + 1); node.chain(key, path); // NOTE: no src means it will observe changes... } }, unchain: function (key, path) { var chains = this._chains; var node = chains[key]; // unchain rest of path first... if (path && path.length > 1) { var nextKey = firstKey(path); var nextPath = path.slice(nextKey.length + 1); node.unchain(nextKey, nextPath); } // delete node if needed. node.count--; if (node.count <= 0) { delete chains[node._key]; node.destroy(); } }, willChange: function (events) { var chains = this._chains; if (chains) { for (var key in chains) { if (!chains.hasOwnProperty(key)) { continue; } chains[key].willChange(events); } } if (this._parent) { this._parent.chainWillChange(this, this._key, 1, events); } }, chainWillChange: function (chain, path, depth, events) { if (this._key) { path = this._key + "." + path; } if (this._parent) { this._parent.chainWillChange(this, path, depth + 1, events); } else { if (depth > 1) { events.push(this.value(), path); } path = "this." + path; if (this._paths[path] > 0) { events.push(this.value(), path); } } }, chainDidChange: function (chain, path, depth, events) { if (this._key) { path = this._key + "." + path; } if (this._parent) { this._parent.chainDidChange(this, path, depth + 1, events); } else { if (depth > 1) { events.push(this.value(), path); } path = "this." + path; if (this._paths[path] > 0) { events.push(this.value(), path); } } }, didChange: function (events) { // invalidate my own value first. if (this._watching) { var obj = this._parent.value(); if (obj !== this._object) { removeChainWatcher(this._object, this._key, this); this._object = obj; addChainWatcher(obj, this._key, this); } this._value = undefined; // Special-case: the EachProxy relies on immediate evaluation to // establish its observers. if (this._parent && this._parent._key === "@each") { this.value(); } } // then notify chains... var chains = this._chains; if (chains) { for (var key in chains) { if (!chains.hasOwnProperty(key)) { continue; } chains[key].didChange(events); } } // if no events are passed in then we only care about the above wiring update if (events === null) { return; } // and finally tell parent about my path changing... if (this._parent) { this._parent.chainDidChange(this, this._key, 1, events); } } }; function finishChains(obj) { // We only create meta if we really have to var m = obj["__ember_meta__"]; var chains, chainWatchers, chainNodes; if (m) { // finish any current chains node watchers that reference obj chainWatchers = m.chainWatchers; if (chainWatchers) { for (var key in chainWatchers) { if (!chainWatchers.hasOwnProperty(key)) { continue; } chainNodes = chainWatchers[key]; if (chainNodes) { for (var i = 0, l = chainNodes.length; i < l; i++) { chainNodes[i].didChange(null); } } } } // copy chains from prototype chains = m.chains; if (chains && chains.value() !== obj) { utils.meta(obj).chains = chains = chains.copy(obj); } } } }); enifed('ember-metal/computed', ['exports', 'ember-metal/property_set', 'ember-metal/utils', 'ember-metal/expand_properties', 'ember-metal/error', 'ember-metal/properties', 'ember-metal/property_events', 'ember-metal/dependent_keys'], function (exports, property_set, utils, expandProperties, EmberError, properties, property_events, dependent_keys) { 'use strict'; exports.ComputedProperty = ComputedProperty; exports.computed = computed; exports.cacheFor = cacheFor; var metaFor = utils.meta; function UNDEFINED() {} // .......................................................... // COMPUTED PROPERTY // /** A computed property transforms an object's function into a property. By default the function backing the computed property will only be called once and the result will be cached. You can specify various properties that your computed property depends on. This will force the cached result to be recomputed if the dependencies are modified. In the following example we declare a computed property (by calling `.property()` on the fullName function) and setup the property dependencies (depending on firstName and lastName). The fullName function will be called once (regardless of how many times it is accessed) as long as its dependencies have not changed. Once firstName or lastName are updated any future calls (or anything bound) to fullName will incorporate the new values. ```javascript var Person = Ember.Object.extend({ // these will be supplied by `create` firstName: null, lastName: null, fullName: function() { var firstName = this.get('firstName'); var lastName = this.get('lastName'); return firstName + ' ' + lastName; }.property('firstName', 'lastName') }); var tom = Person.create({ firstName: 'Tom', lastName: 'Dale' }); tom.get('fullName') // 'Tom Dale' ``` You can also define what Ember should do when setting a computed property. If you try to set a computed property, it will be invoked with the key and value you want to set it to. You can also accept the previous value as the third parameter. ```javascript var Person = Ember.Object.extend({ // these will be supplied by `create` firstName: null, lastName: null, fullName: function(key, value, oldValue) { // getter if (arguments.length === 1) { var firstName = this.get('firstName'); var lastName = this.get('lastName'); return firstName + ' ' + lastName; // setter } else { var name = value.split(' '); this.set('firstName', name[0]); this.set('lastName', name[1]); return value; } }.property('firstName', 'lastName') }); var person = Person.create(); person.set('fullName', 'Peter Wagenet'); person.get('firstName'); // 'Peter' person.get('lastName'); // 'Wagenet' ``` @class ComputedProperty @namespace Ember @constructor */ function ComputedProperty(config, opts) { this.isDescriptor = true; if (typeof config === "function") { config.__ember_arity = config.length; this._getter = config; if (config.__ember_arity > 1) { Ember.deprecate("Using the same function as getter and setter is deprecated.", false, { url: "http://emberjs.com/deprecations/v1.x/#toc_deprecate-using-the-same-function-as-getter-and-setter-in-computed-properties" }); this._setter = config; } } else { this._getter = config.get; this._setter = config.set; if (this._setter && this._setter.__ember_arity === undefined) { this._setter.__ember_arity = this._setter.length; } } this._dependentKeys = undefined; this._suspended = undefined; this._meta = undefined; Ember.deprecate("Passing opts.cacheable to the CP constructor is deprecated. Invoke `volatile()` on the CP instead.", !opts || !opts.hasOwnProperty("cacheable")); this._cacheable = opts && opts.cacheable !== undefined ? opts.cacheable : true; // TODO: Set always to `true` once this deprecation is gone. this._dependentKeys = opts && opts.dependentKeys; Ember.deprecate("Passing opts.readOnly to the CP constructor is deprecated. All CPs are writable by default. You can invoke `readOnly()` on the CP to change this.", !opts || !opts.hasOwnProperty("readOnly")); this._readOnly = opts && (opts.readOnly !== undefined || !!opts.readOnly) || false; // TODO: Set always to `false` once this deprecation is gone. } ComputedProperty.prototype = new properties.Descriptor(); var ComputedPropertyPrototype = ComputedProperty.prototype; /** Properties are cacheable by default. Computed property will automatically cache the return value of your function until one of the dependent keys changes. Call `volatile()` to set it into non-cached mode. When in this mode the computed property will not automatically cache the return value. However, if a property is properly observable, there is no reason to disable caching. @method cacheable @param {Boolean} aFlag optional set to `false` to disable caching @return {Ember.ComputedProperty} this @chainable @deprecated All computed properties are cacheble by default. Use `volatile()` instead to opt-out to caching. */ ComputedPropertyPrototype.cacheable = function (aFlag) { Ember.deprecate("ComputedProperty.cacheable() is deprecated. All computed properties are cacheable by default."); this._cacheable = aFlag !== false; return this; }; /** Call on a computed property to set it into non-cached mode. When in this mode the computed property will not automatically cache the return value. ```javascript var outsideService = Ember.Object.extend({ value: function() { return OutsideService.getValue(); }.property().volatile() }).create(); ``` @method volatile @return {Ember.ComputedProperty} this @chainable */ ComputedPropertyPrototype["volatile"] = function () { this._cacheable = false; return this; }; /** Call on a computed property to set it into read-only mode. When in this mode the computed property will throw an error when set. ```javascript var Person = Ember.Object.extend({ guid: function() { return 'guid-guid-guid'; }.property().readOnly() }); var person = Person.create(); person.set('guid', 'new-guid'); // will throw an exception ``` @method readOnly @return {Ember.ComputedProperty} this @chainable */ ComputedPropertyPrototype.readOnly = function (readOnly) { Ember.deprecate("Passing arguments to ComputedProperty.readOnly() is deprecated.", arguments.length === 0); this._readOnly = readOnly === undefined || !!readOnly; // Force to true once this deprecation is gone Ember.assert("Computed properties that define a setter using the new syntax cannot be read-only", !(this._readOnly && this._setter && this._setter !== this._getter)); return this; }; /** Sets the dependent keys on this computed property. Pass any number of arguments containing key paths that this computed property depends on. ```javascript var President = Ember.Object.extend({ fullName: computed(function() { return this.get('firstName') + ' ' + this.get('lastName'); // Tell Ember that this computed property depends on firstName // and lastName }).property('firstName', 'lastName') }); var president = President.create({ firstName: 'Barack', lastName: 'Obama' }); president.get('fullName'); // 'Barack Obama' ``` @method property @param {String} path* zero or more property paths @return {Ember.ComputedProperty} this @chainable */ ComputedPropertyPrototype.property = function () { var args; var addArg = function (property) { args.push(property); }; args = []; for (var i = 0, l = arguments.length; i < l; i++) { expandProperties['default'](arguments[i], addArg); } this._dependentKeys = args; return this; }; /** In some cases, you may want to annotate computed properties with additional metadata about how they function or what values they operate on. For example, computed property functions may close over variables that are then no longer available for introspection. You can pass a hash of these values to a computed property like this: ``` person: function() { var personId = this.get('personId'); return App.Person.create({ id: personId }); }.property().meta({ type: App.Person }) ``` The hash that you pass to the `meta()` function will be saved on the computed property descriptor under the `_meta` key. Ember runtime exposes a public API for retrieving these values from classes, via the `metaForProperty()` function. @method meta @param {Hash} meta @chainable */ ComputedPropertyPrototype.meta = function (meta) { if (arguments.length === 0) { return this._meta || {}; } else { this._meta = meta; return this; } }; /* impl descriptor API */ ComputedPropertyPrototype.didChange = function (obj, keyName) { // _suspended is set via a CP.set to ensure we don't clear // the cached value set by the setter if (this._cacheable && this._suspended !== obj) { var meta = metaFor(obj); if (meta.cache && meta.cache[keyName] !== undefined) { meta.cache[keyName] = undefined; dependent_keys.removeDependentKeys(this, obj, keyName, meta); } } }; function finishChains(chainNodes) { for (var i = 0, l = chainNodes.length; i < l; i++) { chainNodes[i].didChange(null); } } /** Access the value of the function backing the computed property. If this property has already been cached, return the cached result. Otherwise, call the function passing the property name as an argument. ```javascript var Person = Ember.Object.extend({ fullName: function(keyName) { // the keyName parameter is 'fullName' in this case. return this.get('firstName') + ' ' + this.get('lastName'); }.property('firstName', 'lastName') }); var tom = Person.create({ firstName: 'Tom', lastName: 'Dale' }); tom.get('fullName') // 'Tom Dale' ``` @method get @param {String} keyName The key being accessed. @return {Object} The return value of the function backing the CP. */ ComputedPropertyPrototype.get = function (obj, keyName) { var ret, cache, meta, chainNodes; if (this._cacheable) { meta = metaFor(obj); cache = meta.cache; var result = cache && cache[keyName]; if (result === UNDEFINED) { return undefined; } else if (result !== undefined) { return result; } ret = this._getter.call(obj, keyName); cache = meta.cache; if (!cache) { cache = meta.cache = {}; } if (ret === undefined) { cache[keyName] = UNDEFINED; } else { cache[keyName] = ret; } chainNodes = meta.chainWatchers && meta.chainWatchers[keyName]; if (chainNodes) { finishChains(chainNodes); } dependent_keys.addDependentKeys(this, obj, keyName, meta); } else { ret = this._getter.call(obj, keyName); } return ret; }; /** Set the value of a computed property. If the function that backs your computed property does not accept arguments then the default action for setting would be to define the property on the current object, and set the value of the property to the value being set. Generally speaking if you intend for your computed property to be set your backing function should accept either two or three arguments. ```javascript var Person = Ember.Object.extend({ // these will be supplied by `create` firstName: null, lastName: null, fullName: function(key, value, oldValue) { // getter if (arguments.length === 1) { var firstName = this.get('firstName'); var lastName = this.get('lastName'); return firstName + ' ' + lastName; // setter } else { var name = value.split(' '); this.set('firstName', name[0]); this.set('lastName', name[1]); return value; } }.property('firstName', 'lastName') }); var person = Person.create(); person.set('fullName', 'Peter Wagenet'); person.get('firstName'); // 'Peter' person.get('lastName'); // 'Wagenet' ``` @method set @param {String} keyName The key being accessed. @param {Object} newValue The new value being assigned. @param {String} oldValue The old value being replaced. @return {Object} The return value of the function backing the CP. */ ComputedPropertyPrototype.set = function computedPropertySetWithSuspend(obj, keyName, value) { var oldSuspended = this._suspended; this._suspended = obj; try { this._set(obj, keyName, value); } finally { this._suspended = oldSuspended; } }; ComputedPropertyPrototype._set = function computedPropertySet(obj, keyName, value) { var cacheable = this._cacheable; var setter = this._setter; var meta = metaFor(obj, cacheable); var cache = meta.cache; var hadCachedValue = false; var cachedValue, ret; if (this._readOnly) { throw new EmberError['default']("Cannot set read-only property \"" + keyName + "\" on object: " + utils.inspect(obj)); } if (cacheable && cache && cache[keyName] !== undefined) { if (cache[keyName] !== UNDEFINED) { cachedValue = cache[keyName]; } hadCachedValue = true; } if (!setter) { properties.defineProperty(obj, keyName, null, cachedValue); property_set.set(obj, keyName, value); return; } else if (setter.__ember_arity === 2) { // Is there any way of deprecate this in a sensitive way? // Maybe now that getters and setters are the prefered options we can.... ret = setter.call(obj, keyName, value); } else { ret = setter.call(obj, keyName, value, cachedValue); } if (hadCachedValue && cachedValue === ret) { return; } var watched = meta.watching[keyName]; if (watched) { property_events.propertyWillChange(obj, keyName); } if (hadCachedValue) { cache[keyName] = undefined; } if (cacheable) { if (!hadCachedValue) { dependent_keys.addDependentKeys(this, obj, keyName, meta); } if (!cache) { cache = meta.cache = {}; } if (ret === undefined) { cache[keyName] = UNDEFINED; } else { cache[keyName] = ret; } } if (watched) { property_events.propertyDidChange(obj, keyName); } return ret; }; /* called before property is overridden */ ComputedPropertyPrototype.teardown = function (obj, keyName) { var meta = metaFor(obj); if (meta.cache) { if (keyName in meta.cache) { dependent_keys.removeDependentKeys(this, obj, keyName, meta); } if (this._cacheable) { delete meta.cache[keyName]; } } return null; // no value to restore }; /** This helper returns a new property descriptor that wraps the passed computed property function. You can use this helper to define properties with mixins or via `Ember.defineProperty()`. The function you pass will be used to both get and set property values. The function should accept two parameters, key and value. If value is not undefined you should set the value first. In either case return the current value of the property. A computed property defined in this way might look like this: ```js var Person = Ember.Object.extend({ firstName: 'Betty', lastName: 'Jones', fullName: Ember.computed('firstName', 'lastName', function(key, value) { return this.get('firstName') + ' ' + this.get('lastName'); }) }); var client = Person.create(); client.get('fullName'); // 'Betty Jones' client.set('lastName', 'Fuller'); client.get('fullName'); // 'Betty Fuller' ``` _Note: This is the preferred way to define computed properties when writing third-party libraries that depend on or use Ember, since there is no guarantee that the user will have prototype extensions enabled._ You might use this method if you disabled [Prototype Extensions](http://emberjs.com/guides/configuring-ember/disabling-prototype-extensions/). The alternative syntax might look like this (if prototype extensions are enabled, which is the default behavior): ```js fullName: function () { return this.get('firstName') + ' ' + this.get('lastName'); }.property('firstName', 'lastName') ``` @class computed @namespace Ember @constructor @static @param {String} [dependentKeys*] Optional dependent keys that trigger this computed property. @param {Function} func The computed property function. @return {Ember.ComputedProperty} property descriptor instance */ function computed(func) { var args; if (arguments.length > 1) { args = [].slice.call(arguments); func = args.pop(); } var cp = new ComputedProperty(func); if (args) { cp.property.apply(cp, args); } return cp; } /** Returns the cached value for a property, if one exists. This can be useful for peeking at the value of a computed property that is generated lazily, without accidentally causing it to be created. @method cacheFor @for Ember @param {Object} obj the object whose property you want to check @param {String} key the name of the property whose cached value you want to return @return {Object} the cached value */ function cacheFor(obj, key) { var meta = obj["__ember_meta__"]; var cache = meta && meta.cache; var ret = cache && cache[key]; if (ret === UNDEFINED) { return undefined; } return ret; } cacheFor.set = function (cache, key, value) { if (value === undefined) { cache[key] = UNDEFINED; } else { cache[key] = value; } }; cacheFor.get = function (cache, key) { var ret = cache[key]; if (ret === UNDEFINED) { return undefined; } return ret; }; cacheFor.remove = function (cache, key) { cache[key] = undefined; }; }); enifed('ember-metal/computed_macros', ['exports', 'ember-metal/core', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/computed', 'ember-metal/is_empty', 'ember-metal/is_none', 'ember-metal/alias'], function (exports, Ember, property_get, property_set, computed, isEmpty, isNone, alias) { 'use strict'; exports.empty = empty; exports.notEmpty = notEmpty; exports.none = none; exports.not = not; exports.bool = bool; exports.match = match; exports.equal = equal; exports.gt = gt; exports.gte = gte; exports.lt = lt; exports.lte = lte; exports.oneWay = oneWay; exports.readOnly = readOnly; exports.defaultTo = defaultTo; exports.deprecatingAlias = deprecatingAlias; function getProperties(self, propertyNames) { var ret = {}; for (var i = 0; i < propertyNames.length; i++) { ret[propertyNames[i]] = property_get.get(self, propertyNames[i]); } return ret; } function generateComputedWithProperties(macro) { return function () { for (var _len = arguments.length, properties = Array(_len), _key = 0; _key < _len; _key++) { properties[_key] = arguments[_key]; } var computedFunc = computed.computed(function () { return macro.apply(this, [getProperties(this, properties)]); }); return computedFunc.property.apply(computedFunc, properties); }; } /** A computed property that returns true if the value of the dependent property is null, an empty string, empty array, or empty function. Example ```javascript var ToDoList = Ember.Object.extend({ isDone: Ember.computed.empty('todos') }); var todoList = ToDoList.create({ todos: ['Unit Test', 'Documentation', 'Release'] }); todoList.get('isDone'); // false todoList.get('todos').clear(); todoList.get('isDone'); // true ``` @since 1.6.0 @method empty @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which negate the original value for property */ function empty(dependentKey) { return computed.computed(dependentKey + ".length", function () { return isEmpty['default'](property_get.get(this, dependentKey)); }); } /** A computed property that returns true if the value of the dependent property is NOT null, an empty string, empty array, or empty function. Example ```javascript var Hamster = Ember.Object.extend({ hasStuff: Ember.computed.notEmpty('backpack') }); var hamster = Hamster.create({ backpack: ['Food', 'Sleeping Bag', 'Tent'] }); hamster.get('hasStuff'); // true hamster.get('backpack').clear(); // [] hamster.get('hasStuff'); // false ``` @method notEmpty @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which returns true if original value for property is not empty. */ function notEmpty(dependentKey) { return computed.computed(dependentKey + ".length", function () { return !isEmpty['default'](property_get.get(this, dependentKey)); }); } /** A computed property that returns true if the value of the dependent property is null or undefined. This avoids errors from JSLint complaining about use of ==, which can be technically confusing. Example ```javascript var Hamster = Ember.Object.extend({ isHungry: Ember.computed.none('food') }); var hamster = Hamster.create(); hamster.get('isHungry'); // true hamster.set('food', 'Banana'); hamster.get('isHungry'); // false hamster.set('food', null); hamster.get('isHungry'); // true ``` @method none @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which returns true if original value for property is null or undefined. */ function none(dependentKey) { return computed.computed(dependentKey, function () { return isNone['default'](property_get.get(this, dependentKey)); }); } /** A computed property that returns the inverse boolean value of the original value for the dependent property. Example ```javascript var User = Ember.Object.extend({ isAnonymous: Ember.computed.not('loggedIn') }); var user = User.create({loggedIn: false}); user.get('isAnonymous'); // true user.set('loggedIn', true); user.get('isAnonymous'); // false ``` @method not @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which returns inverse of the original value for property */ function not(dependentKey) { return computed.computed(dependentKey, function () { return !property_get.get(this, dependentKey); }); } /** A computed property that converts the provided dependent property into a boolean value. ```javascript var Hamster = Ember.Object.extend({ hasBananas: Ember.computed.bool('numBananas') }); var hamster = Hamster.create(); hamster.get('hasBananas'); // false hamster.set('numBananas', 0); hamster.get('hasBananas'); // false hamster.set('numBananas', 1); hamster.get('hasBananas'); // true hamster.set('numBananas', null); hamster.get('hasBananas'); // false ``` @method bool @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which converts to boolean the original value for property */ function bool(dependentKey) { return computed.computed(dependentKey, function () { return !!property_get.get(this, dependentKey); }); } /** A computed property which matches the original value for the dependent property against a given RegExp, returning `true` if they values matches the RegExp and `false` if it does not. Example ```javascript var User = Ember.Object.extend({ hasValidEmail: Ember.computed.match('email', /^.+@.+\..+$/) }); var user = User.create({loggedIn: false}); user.get('hasValidEmail'); // false user.set('email', ''); user.get('hasValidEmail'); // false user.set('email', 'ember_hamster@example.com'); user.get('hasValidEmail'); // true ``` @method match @for Ember.computed @param {String} dependentKey @param {RegExp} regexp @return {Ember.ComputedProperty} computed property which match the original value for property against a given RegExp */ function match(dependentKey, regexp) { return computed.computed(dependentKey, function () { var value = property_get.get(this, dependentKey); return typeof value === "string" ? regexp.test(value) : false; }); } /** A computed property that returns true if the provided dependent property is equal to the given value. Example ```javascript var Hamster = Ember.Object.extend({ napTime: Ember.computed.equal('state', 'sleepy') }); var hamster = Hamster.create(); hamster.get('napTime'); // false hamster.set('state', 'sleepy'); hamster.get('napTime'); // true hamster.set('state', 'hungry'); hamster.get('napTime'); // false ``` @method equal @for Ember.computed @param {String} dependentKey @param {String|Number|Object} value @return {Ember.ComputedProperty} computed property which returns true if the original value for property is equal to the given value. */ function equal(dependentKey, value) { return computed.computed(dependentKey, function () { return property_get.get(this, dependentKey) === value; }); } /** A computed property that returns true if the provided dependent property is greater than the provided value. Example ```javascript var Hamster = Ember.Object.extend({ hasTooManyBananas: Ember.computed.gt('numBananas', 10) }); var hamster = Hamster.create(); hamster.get('hasTooManyBananas'); // false hamster.set('numBananas', 3); hamster.get('hasTooManyBananas'); // false hamster.set('numBananas', 11); hamster.get('hasTooManyBananas'); // true ``` @method gt @for Ember.computed @param {String} dependentKey @param {Number} value @return {Ember.ComputedProperty} computed property which returns true if the original value for property is greater than given value. */ function gt(dependentKey, value) { return computed.computed(dependentKey, function () { return property_get.get(this, dependentKey) > value; }); } /** A computed property that returns true if the provided dependent property is greater than or equal to the provided value. Example ```javascript var Hamster = Ember.Object.extend({ hasTooManyBananas: Ember.computed.gte('numBananas', 10) }); var hamster = Hamster.create(); hamster.get('hasTooManyBananas'); // false hamster.set('numBananas', 3); hamster.get('hasTooManyBananas'); // false hamster.set('numBananas', 10); hamster.get('hasTooManyBananas'); // true ``` @method gte @for Ember.computed @param {String} dependentKey @param {Number} value @return {Ember.ComputedProperty} computed property which returns true if the original value for property is greater or equal then given value. */ function gte(dependentKey, value) { return computed.computed(dependentKey, function () { return property_get.get(this, dependentKey) >= value; }); } /** A computed property that returns true if the provided dependent property is less than the provided value. Example ```javascript var Hamster = Ember.Object.extend({ needsMoreBananas: Ember.computed.lt('numBananas', 3) }); var hamster = Hamster.create(); hamster.get('needsMoreBananas'); // true hamster.set('numBananas', 3); hamster.get('needsMoreBananas'); // false hamster.set('numBananas', 2); hamster.get('needsMoreBananas'); // true ``` @method lt @for Ember.computed @param {String} dependentKey @param {Number} value @return {Ember.ComputedProperty} computed property which returns true if the original value for property is less then given value. */ function lt(dependentKey, value) { return computed.computed(dependentKey, function () { return property_get.get(this, dependentKey) < value; }); } /** A computed property that returns true if the provided dependent property is less than or equal to the provided value. Example ```javascript var Hamster = Ember.Object.extend({ needsMoreBananas: Ember.computed.lte('numBananas', 3) }); var hamster = Hamster.create(); hamster.get('needsMoreBananas'); // true hamster.set('numBananas', 5); hamster.get('needsMoreBananas'); // false hamster.set('numBananas', 3); hamster.get('needsMoreBananas'); // true ``` @method lte @for Ember.computed @param {String} dependentKey @param {Number} value @return {Ember.ComputedProperty} computed property which returns true if the original value for property is less or equal than given value. */ function lte(dependentKey, value) { return computed.computed(dependentKey, function () { return property_get.get(this, dependentKey) <= value; }); } /** A computed property that performs a logical `and` on the original values for the provided dependent properties. Example ```javascript var Hamster = Ember.Object.extend({ readyForCamp: Ember.computed.and('hasTent', 'hasBackpack') }); var hamster = Hamster.create(); hamster.get('readyForCamp'); // false hamster.set('hasTent', true); hamster.get('readyForCamp'); // false hamster.set('hasBackpack', true); hamster.get('readyForCamp'); // true hamster.set('hasBackpack', 'Yes'); hamster.get('readyForCamp'); // 'Yes' ``` @method and @for Ember.computed @param {String} dependentKey* @return {Ember.ComputedProperty} computed property which performs a logical `and` on the values of all the original values for properties. */ var and = generateComputedWithProperties(function (properties) { var value; for (var key in properties) { value = properties[key]; if (properties.hasOwnProperty(key) && !value) { return false; } } return value; }); var or = generateComputedWithProperties(function (properties) { for (var key in properties) { if (properties.hasOwnProperty(key) && properties[key]) { return properties[key]; } } return false; }); var any = generateComputedWithProperties(function (properties) { for (var key in properties) { if (properties.hasOwnProperty(key) && properties[key]) { return properties[key]; } } return null; }); var collect = generateComputedWithProperties(function (properties) { var res = Ember['default'].A(); for (var key in properties) { if (properties.hasOwnProperty(key)) { if (isNone['default'](properties[key])) { res.push(null); } else { res.push(properties[key]); } } } return res; }); function oneWay(dependentKey) { return alias['default'](dependentKey).oneWay(); } /** This is a more semantically meaningful alias of `computed.oneWay`, whose name is somewhat ambiguous as to which direction the data flows. @method reads @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which creates a one way computed property to the original value for property. */ /** Where `computed.oneWay` provides oneWay bindings, `computed.readOnly` provides a readOnly one way binding. Very often when using `computed.oneWay` one does not also want changes to propagate back up, as they will replace the value. This prevents the reverse flow, and also throws an exception when it occurs. Example ```javascript var User = Ember.Object.extend({ firstName: null, lastName: null, nickName: Ember.computed.readOnly('firstName') }); var teddy = User.create({ firstName: 'Teddy', lastName: 'Zeenny' }); teddy.get('nickName'); // 'Teddy' teddy.set('nickName', 'TeddyBear'); // throws Exception // throw new Ember.Error('Cannot Set: nickName on: ' );` teddy.get('firstName'); // 'Teddy' ``` @method readOnly @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which creates a one way computed property to the original value for property. @since 1.5.0 */ function readOnly(dependentKey) { return alias['default'](dependentKey).readOnly(); } /** A computed property that acts like a standard getter and setter, but returns the value at the provided `defaultPath` if the property itself has not been set to a value Example ```javascript var Hamster = Ember.Object.extend({ wishList: Ember.computed.defaultTo('favoriteFood') }); var hamster = Hamster.create({ favoriteFood: 'Banana' }); hamster.get('wishList'); // 'Banana' hamster.set('wishList', 'More Unit Tests'); hamster.get('wishList'); // 'More Unit Tests' hamster.get('favoriteFood'); // 'Banana' ``` @method defaultTo @for Ember.computed @param {String} defaultPath @return {Ember.ComputedProperty} computed property which acts like a standard getter and setter, but defaults to the value from `defaultPath`. @deprecated Use `Ember.computed.oneWay` or custom CP with default instead. */ function defaultTo(defaultPath) { return computed.computed({ get: function (key) { Ember['default'].deprecate("Usage of Ember.computed.defaultTo is deprecated, use `Ember.computed.oneWay` instead."); return property_get.get(this, defaultPath); }, set: function (key, newValue, cachedValue) { Ember['default'].deprecate("Usage of Ember.computed.defaultTo is deprecated, use `Ember.computed.oneWay` instead."); return newValue != null ? newValue : property_get.get(this, defaultPath); } }); } /** Creates a new property that is an alias for another property on an object. Calls to `get` or `set` this property behave as though they were called on the original property, but also print a deprecation warning. @method deprecatingAlias @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which creates an alias with a deprecation to the original value for property. @since 1.7.0 */ function deprecatingAlias(dependentKey) { return computed.computed(dependentKey, { get: function (key) { Ember['default'].deprecate("Usage of `" + key + "` is deprecated, use `" + dependentKey + "` instead."); return property_get.get(this, dependentKey); }, set: function (key, value) { Ember['default'].deprecate("Usage of `" + key + "` is deprecated, use `" + dependentKey + "` instead."); property_set.set(this, dependentKey, value); return value; } }); } exports.and = and; exports.or = or; exports.any = any; exports.collect = collect; }); enifed('ember-metal/core', ['exports'], function (exports) { 'use strict'; exports.K = K; /*globals Ember:true,ENV,EmberENV */ /** @module ember @submodule ember-metal */ /** This namespace contains all Ember methods and functions. Future versions of Ember may overwrite this namespace and therefore, you should avoid adding any new properties. You can also use the shorthand `Em` instead of `Ember`. At the heart of Ember is Ember-Runtime, a set of core functions that provide cross-platform compatibility and object property observing. Ember-Runtime is small and performance-focused so you can use it alongside other cross-platform libraries such as jQuery. For more details, see [Ember-Runtime](http://emberjs.com/api/modules/ember-runtime.html). @class Ember @static @version 1.13.0-beta.2 */ if ('undefined' === typeof Ember) { // Create core object. Make it act like an instance of Ember.Namespace so that // objects assigned to it are given a sane string representation. Ember = {}; } // Default imports, exports and lookup to the global object; var global = mainContext || {}; // jshint ignore:line Ember.imports = Ember.imports || global; Ember.lookup = Ember.lookup || global; var emExports = Ember.exports = Ember.exports || global; // aliases needed to keep minifiers from removing the global context emExports.Em = emExports.Ember = Ember; // Make sure these are set whether Ember was already defined or not Ember.isNamespace = true; Ember.toString = function () { return 'Ember'; }; /** The semantic version. @property VERSION @type String @default '1.13.0-beta.2' @static */ Ember.VERSION = '1.13.0-beta.2'; /** The hash of environment variables used to control various configuration settings. To specify your own or override default settings, add the desired properties to a global hash named `EmberENV` (or `ENV` for backwards compatibility with earlier versions of Ember). The `EmberENV` hash must be created before loading Ember. @property ENV @type Hash */ if (Ember.ENV) { // do nothing if Ember.ENV is already setup Ember.assert('Ember.ENV should be an object.', 'object' !== typeof Ember.ENV); } else if ('undefined' !== typeof EmberENV) { Ember.ENV = EmberENV; } else if ('undefined' !== typeof ENV) { Ember.ENV = ENV; } else { Ember.ENV = {}; } Ember.config = Ember.config || {}; // We disable the RANGE API by default for performance reasons if ('undefined' === typeof Ember.ENV.DISABLE_RANGE_API) { Ember.ENV.DISABLE_RANGE_API = true; } /** The hash of enabled Canary features. Add to this, any canary features before creating your application. Alternatively (and recommended), you can also define `EmberENV.FEATURES` if you need to enable features flagged at runtime. @class FEATURES @namespace Ember @static @since 1.1.0 */ Ember.FEATURES = {"features-stripped-test":false,"ember-routing-named-substates":true,"mandatory-setter":true,"ember-htmlbars-component-generation":false,"ember-htmlbars-component-helper":true,"ember-htmlbars-inline-if-helper":true,"ember-htmlbars-attribute-syntax":true,"ember-routing-transitioning-classes":true,"ember-testing-checkbox-helpers":false,"ember-metal-stream":false,"ember-application-instance-initializers":true,"ember-application-initializer-context":true,"ember-router-willtransition":true,"ember-application-visit":false,"ember-views-component-block-info":true,"ember-routing-core-outlet":false,"ember-libraries-isregistered":false,"ember-routing-htmlbars-improved-actions":true}; //jshint ignore:line if (Ember.ENV.FEATURES) { for (var feature in Ember.ENV.FEATURES) { if (Ember.ENV.FEATURES.hasOwnProperty(feature)) { Ember.FEATURES[feature] = Ember.ENV.FEATURES[feature]; } } } /** Determine whether the specified `feature` is enabled. Used by Ember's build tools to exclude experimental features from beta/stable builds. You can define the following configuration options: * `EmberENV.ENABLE_ALL_FEATURES` - force all features to be enabled. * `EmberENV.ENABLE_OPTIONAL_FEATURES` - enable any features that have not been explicitly enabled/disabled. @method isEnabled @param {String} feature The feature to check @return {Boolean} @for Ember.FEATURES @since 1.1.0 */ Ember.FEATURES.isEnabled = function (feature) { var featureValue = Ember.FEATURES[feature]; if (Ember.ENV.ENABLE_ALL_FEATURES) { return true; } else if (featureValue === true || featureValue === false || featureValue === undefined) { return featureValue; } else if (Ember.ENV.ENABLE_OPTIONAL_FEATURES) { return true; } else { return false; } }; // .......................................................... // BOOTSTRAP // /** Determines whether Ember should add to `Array`, `Function`, and `String` native object prototypes, a few extra methods in order to provide a more friendly API. We generally recommend leaving this option set to true however, if you need to turn it off, you can add the configuration property `EXTEND_PROTOTYPES` to `EmberENV` and set it to `false`. Note, when disabled (the default configuration for Ember Addons), you will instead have to access all methods and functions from the Ember namespace. @property EXTEND_PROTOTYPES @type Boolean @default true @for Ember */ Ember.EXTEND_PROTOTYPES = Ember.ENV.EXTEND_PROTOTYPES; if (typeof Ember.EXTEND_PROTOTYPES === 'undefined') { Ember.EXTEND_PROTOTYPES = true; } /** The `LOG_STACKTRACE_ON_DEPRECATION` property, when true, tells Ember to log a full stack trace during deprecation warnings. @property LOG_STACKTRACE_ON_DEPRECATION @type Boolean @default true */ Ember.LOG_STACKTRACE_ON_DEPRECATION = Ember.ENV.LOG_STACKTRACE_ON_DEPRECATION !== false; /** The `SHIM_ES5` property, when true, tells Ember to add ECMAScript 5 Array shims to older browsers. @property SHIM_ES5 @type Boolean @default Ember.EXTEND_PROTOTYPES */ Ember.SHIM_ES5 = Ember.ENV.SHIM_ES5 === false ? false : Ember.EXTEND_PROTOTYPES; /** The `LOG_VERSION` property, when true, tells Ember to log versions of all dependent libraries in use. @property LOG_VERSION @type Boolean @default true */ Ember.LOG_VERSION = Ember.ENV.LOG_VERSION === false ? false : true; /** An empty function useful for some operations. Always returns `this`. @method K @private @return {Object} */ function K() { return this; } Ember.K = K; //TODO: ES6 GLOBAL TODO // Stub out the methods defined by the ember-debug package in case it's not loaded if ('undefined' === typeof Ember.assert) { Ember.assert = K; } if ('undefined' === typeof Ember.warn) { Ember.warn = K; } if ('undefined' === typeof Ember.debug) { Ember.debug = K; } if ('undefined' === typeof Ember.runInDebug) { Ember.runInDebug = K; } if ('undefined' === typeof Ember.deprecate) { Ember.deprecate = K; } if ('undefined' === typeof Ember.deprecateFunc) { Ember.deprecateFunc = function (_, func) { return func; }; } exports['default'] = Ember; }); enifed('ember-metal/dependent_keys', ['exports', 'ember-metal/platform/create', 'ember-metal/watching'], function (exports, o_create, watching) { exports.addDependentKeys = addDependentKeys; exports.removeDependentKeys = removeDependentKeys; "REMOVE_USE_STRICT: true"; /** @module ember-metal */ // .......................................................... // DEPENDENT KEYS // // data structure: // meta.deps = { // 'depKey': { // 'keyName': count, // } // } /* This function returns a map of unique dependencies for a given object and key. */ function keysForDep(depsMeta, depKey) { var keys = depsMeta[depKey]; if (!keys) { // if there are no dependencies yet for a the given key // create a new empty list of dependencies for the key keys = depsMeta[depKey] = {}; } else if (!depsMeta.hasOwnProperty(depKey)) { // otherwise if the dependency list is inherited from // a superclass, clone the hash keys = depsMeta[depKey] = o_create['default'](keys); } return keys; } function metaForDeps(meta) { return keysForDep(meta, "deps"); } function addDependentKeys(desc, obj, keyName, meta) { // the descriptor has a list of dependent keys, so // add all of its dependent keys. var depsMeta, idx, len, depKey, keys; var depKeys = desc._dependentKeys; if (!depKeys) { return; } depsMeta = metaForDeps(meta); for (idx = 0, len = depKeys.length; idx < len; idx++) { depKey = depKeys[idx]; // Lookup keys meta for depKey keys = keysForDep(depsMeta, depKey); // Increment the number of times depKey depends on keyName. keys[keyName] = (keys[keyName] || 0) + 1; // Watch the depKey watching.watch(obj, depKey, meta); } } function removeDependentKeys(desc, obj, keyName, meta) { // the descriptor has a list of dependent keys, so // remove all of its dependent keys. var depKeys = desc._dependentKeys; var depsMeta, idx, len, depKey, keys; if (!depKeys) { return; } depsMeta = metaForDeps(meta); for (idx = 0, len = depKeys.length; idx < len; idx++) { depKey = depKeys[idx]; // Lookup keys meta for depKey keys = keysForDep(depsMeta, depKey); // Decrement the number of times depKey depends on keyName. keys[keyName] = (keys[keyName] || 0) - 1; // Unwatch the depKey watching.unwatch(obj, depKey, meta); } } }); enifed('ember-metal/deprecate_property', ['exports', 'ember-metal/core', 'ember-metal/platform/define_property', 'ember-metal/properties', 'ember-metal/property_get', 'ember-metal/property_set'], function (exports, Ember, define_property, properties, property_get, property_set) { 'use strict'; exports.deprecateProperty = deprecateProperty; function deprecateProperty(object, deprecatedKey, newKey) { function deprecate() { Ember['default'].deprecate("Usage of `" + deprecatedKey + "` is deprecated, use `" + newKey + "` instead."); } if (define_property.hasPropertyAccessors) { properties.defineProperty(object, deprecatedKey, { configurable: true, enumerable: false, set: function (value) { deprecate(); property_set.set(this, newKey, value); }, get: function () { deprecate(); return property_get.get(this, newKey); } }); } } }); enifed('ember-metal/dictionary', ['exports', 'ember-metal/platform/create'], function (exports, create) { 'use strict'; exports['default'] = makeDictionary; function makeDictionary(parent) { var dict = create['default'](parent); dict['_dict'] = null; delete dict['_dict']; return dict; } }); enifed('ember-metal/enumerable_utils', ['exports', 'ember-metal/array'], function (exports, ember_metal__array) { 'use strict'; exports.map = map; exports.forEach = forEach; exports.filter = filter; exports.indexOf = indexOf; exports.indexesOf = indexesOf; exports.addObject = addObject; exports.removeObject = removeObject; exports._replace = _replace; exports.replace = replace; exports.intersection = intersection; var splice = Array.prototype.splice; /** * Defines some convenience methods for working with Enumerables. * `Ember.EnumerableUtils` uses `Ember.ArrayPolyfills` when necessary. * * @class EnumerableUtils * @namespace Ember * @static * */ /** * Calls the map function on the passed object with a specified callback. This * uses `Ember.ArrayPolyfill`'s-map method when necessary. * * @method map * @param {Object} obj The object that should be mapped * @param {Function} callback The callback to execute * @param {Object} thisArg Value to use as this when executing *callback* * * @return {Array} An array of mapped values. */ function map(obj, callback, thisArg) { return obj.map ? obj.map(callback, thisArg) : ember_metal__array.map.call(obj, callback, thisArg); } /** * Calls the forEach function on the passed object with a specified callback. This * uses `Ember.ArrayPolyfill`'s-forEach method when necessary. * * @method forEach * @param {Object} obj The object to call forEach on * @param {Function} callback The callback to execute * @param {Object} thisArg Value to use as this when executing *callback* * */ function forEach(obj, callback, thisArg) { return obj.forEach ? obj.forEach(callback, thisArg) : ember_metal__array.forEach.call(obj, callback, thisArg); } /** * Calls the filter function on the passed object with a specified callback. This * uses `Ember.ArrayPolyfill`'s-filter method when necessary. * * @method filter * @param {Object} obj The object to call filter on * @param {Function} callback The callback to execute * @param {Object} thisArg Value to use as this when executing *callback* * * @return {Array} An array containing the filtered values * @since 1.4.0 */ function filter(obj, callback, thisArg) { return obj.filter ? obj.filter(callback, thisArg) : ember_metal__array.filter.call(obj, callback, thisArg); } /** * Calls the indexOf function on the passed object with a specified callback. This * uses `Ember.ArrayPolyfill`'s-indexOf method when necessary. * * @method indexOf * @param {Object} obj The object to call indexOn on * @param {Function} callback The callback to execute * @param {Object} index The index to start searching from * */ function indexOf(obj, element, index) { return obj.indexOf ? obj.indexOf(element, index) : ember_metal__array.indexOf.call(obj, element, index); } /** * Returns an array of indexes of the first occurrences of the passed elements * on the passed object. * * ```javascript * var array = [1, 2, 3, 4, 5]; * Ember.EnumerableUtils.indexesOf(array, [2, 5]); // [1, 4] * * var fubar = "Fubarr"; * Ember.EnumerableUtils.indexesOf(fubar, ['b', 'r']); // [2, 4] * ``` * * @method indexesOf * @param {Object} obj The object to check for element indexes * @param {Array} elements The elements to search for on *obj* * * @return {Array} An array of indexes. * */ function indexesOf(obj, elements) { return elements === undefined ? [] : map(elements, function (item) { return indexOf(obj, item); }); } /** * Adds an object to an array. If the array already includes the object this * method has no effect. * * @method addObject * @param {Array} array The array the passed item should be added to * @param {Object} item The item to add to the passed array * * @return 'undefined' */ function addObject(array, item) { var index = indexOf(array, item); if (index === -1) { array.push(item); } } /** * Removes an object from an array. If the array does not contain the passed * object this method has no effect. * * @method removeObject * @param {Array} array The array to remove the item from. * @param {Object} item The item to remove from the passed array. * * @return 'undefined' */ function removeObject(array, item) { var index = indexOf(array, item); if (index !== -1) { array.splice(index, 1); } } function _replace(array, idx, amt, objects) { var args = [].concat(objects); var ret = []; // https://code.google.com/p/chromium/issues/detail?id=56588 var size = 60000; var start = idx; var ends = amt; var count, chunk; while (args.length) { count = ends > size ? size : ends; if (count <= 0) { count = 0; } chunk = args.splice(0, size); chunk = [start, count].concat(chunk); start += size; ends -= count; ret = ret.concat(splice.apply(array, chunk)); } return ret; } /** * Replaces objects in an array with the passed objects. * * ```javascript * var array = [1,2,3]; * Ember.EnumerableUtils.replace(array, 1, 2, [4, 5]); // [1, 4, 5] * * var array = [1,2,3]; * Ember.EnumerableUtils.replace(array, 1, 1, [4, 5]); // [1, 4, 5, 3] * * var array = [1,2,3]; * Ember.EnumerableUtils.replace(array, 10, 1, [4, 5]); // [1, 2, 3, 4, 5] * ``` * * @method replace * @param {Array} array The array the objects should be inserted into. * @param {Number} idx Starting index in the array to replace. If *idx* >= * length, then append to the end of the array. * @param {Number} amt Number of elements that should be removed from the array, * starting at *idx* * @param {Array} objects An array of zero or more objects that should be * inserted into the array at *idx* * * @return {Array} The modified array. */ function replace(array, idx, amt, objects) { if (array.replace) { return array.replace(idx, amt, objects); } else { return _replace(array, idx, amt, objects); } } /** * Calculates the intersection of two arrays. This method returns a new array * filled with the records that the two passed arrays share with each other. * If there is no intersection, an empty array will be returned. * * ```javascript * var array1 = [1, 2, 3, 4, 5]; * var array2 = [1, 3, 5, 6, 7]; * * Ember.EnumerableUtils.intersection(array1, array2); // [1, 3, 5] * * var array1 = [1, 2, 3]; * var array2 = [4, 5, 6]; * * Ember.EnumerableUtils.intersection(array1, array2); // [] * ``` * * @method intersection * @param {Array} array1 The first array * @param {Array} array2 The second array * * @return {Array} The intersection of the two passed arrays. */ function intersection(array1, array2) { var result = []; forEach(array1, function (element) { if (indexOf(array2, element) >= 0) { result.push(element); } }); return result; } // TODO: this only exists to maintain the existing api, as we move forward it // should only be part of the "global build" via some shim exports['default'] = { _replace: _replace, addObject: addObject, filter: filter, forEach: forEach, indexOf: indexOf, indexesOf: indexesOf, intersection: intersection, map: map, removeObject: removeObject, replace: replace }; }); enifed('ember-metal/environment', ['exports', 'ember-metal/core'], function (exports, Ember) { 'use strict'; var environment; // This code attempts to automatically detect an environment with DOM // by searching for window and document.createElement. An environment // with DOM may disable the DOM functionality of Ember explicitly by // defining a `disableBrowserEnvironment` ENV. var hasDOM = typeof window !== 'undefined' && typeof document !== 'undefined' && typeof document.createElement !== 'undefined' && !Ember['default'].ENV.disableBrowserEnvironment; if (hasDOM) { environment = { hasDOM: true, isChrome: !!window.chrome && !window.opera, isFirefox: typeof InstallTrigger !== 'undefined', location: window.location, history: window.history, userAgent: window.navigator.userAgent, global: window }; } else { environment = { hasDOM: false, isChrome: false, isFirefox: false, location: null, history: null, userAgent: 'Lynx (textmode)', global: null }; } exports['default'] = environment; }); enifed('ember-metal/error', ['exports', 'ember-metal/platform/create'], function (exports, create) { 'use strict'; var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; /** A subclass of the JavaScript Error object for use in Ember. @class Error @namespace Ember @extends Error @constructor */ function EmberError() { var tmp = Error.apply(this, arguments); // Adds a `stack` property to the given error object that will yield the // stack trace at the time captureStackTrace was called. // When collecting the stack trace all frames above the topmost call // to this function, including that call, will be left out of the // stack trace. // This is useful because we can hide Ember implementation details // that are not very helpful for the user. if (Error.captureStackTrace) { Error.captureStackTrace(this, Ember.Error); } // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. for (var idx = 0; idx < errorProps.length; idx++) { this[errorProps[idx]] = tmp[errorProps[idx]]; } } EmberError.prototype = create['default'](Error.prototype); exports['default'] = EmberError; }); enifed('ember-metal/events', ['exports', 'ember-metal/core', 'ember-metal/utils', 'ember-metal/platform/create'], function (exports, Ember, utils, create) { exports.accumulateListeners = accumulateListeners; exports.addListener = addListener; exports.suspendListener = suspendListener; exports.suspendListeners = suspendListeners; exports.watchedEvents = watchedEvents; exports.sendEvent = sendEvent; exports.hasListeners = hasListeners; exports.listenersFor = listenersFor; exports.on = on; exports.removeListener = removeListener; "REMOVE_USE_STRICT: true"; /* listener flags */ var ONCE = 1; var SUSPENDED = 2; /* The event system uses a series of nested hashes to store listeners on an object. When a listener is registered, or when an event arrives, these hashes are consulted to determine which target and action pair to invoke. The hashes are stored in the object's meta hash, and look like this: // Object's meta hash { listeners: { // variable name: `listenerSet` "foo:changed": [ // variable name: `actions` target, method, flags ] } } */ function indexOf(array, target, method) { var index = -1; // hashes are added to the end of the event array // so it makes sense to start searching at the end // of the array and search in reverse for (var i = array.length - 3; i >= 0; i -= 3) { if (target === array[i] && method === array[i + 1]) { index = i; break; } } return index; } function actionsFor(obj, eventName) { var meta = utils.meta(obj, true); var actions; var listeners = meta.listeners; if (!listeners) { listeners = meta.listeners = create['default'](null); listeners.__source__ = obj; } else if (listeners.__source__ !== obj) { // setup inherited copy of the listeners object listeners = meta.listeners = create['default'](listeners); listeners.__source__ = obj; } actions = listeners[eventName]; // if there are actions, but the eventName doesn't exist in our listeners, then copy them from the prototype if (actions && actions.__source__ !== obj) { actions = listeners[eventName] = listeners[eventName].slice(); actions.__source__ = obj; } else if (!actions) { actions = listeners[eventName] = []; actions.__source__ = obj; } return actions; } function accumulateListeners(obj, eventName, otherActions) { var meta = obj["__ember_meta__"]; var actions = meta && meta.listeners && meta.listeners[eventName]; if (!actions) { return; } var newActions = []; for (var i = actions.length - 3; i >= 0; i -= 3) { var target = actions[i]; var method = actions[i + 1]; var flags = actions[i + 2]; var actionIndex = indexOf(otherActions, target, method); if (actionIndex === -1) { otherActions.push(target, method, flags); newActions.push(target, method, flags); } } return newActions; } /** Add an event listener @method addListener @for Ember @param obj @param {String} eventName @param {Object|Function} target A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @param {Boolean} once A flag whether a function should only be called once */ function addListener(obj, eventName, target, method, once) { Ember['default'].assert("You must pass at least an object and event name to Ember.addListener", !!obj && !!eventName); if (!method && "function" === typeof target) { method = target; target = null; } var actions = actionsFor(obj, eventName); var actionIndex = indexOf(actions, target, method); var flags = 0; if (once) { flags |= ONCE; } if (actionIndex !== -1) { return; } actions.push(target, method, flags); if ("function" === typeof obj.didAddListener) { obj.didAddListener(eventName, target, method); } } /** Remove an event listener Arguments should match those passed to `Ember.addListener`. @method removeListener @for Ember @param obj @param {String} eventName @param {Object|Function} target A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` */ function removeListener(obj, eventName, target, method) { Ember['default'].assert("You must pass at least an object and event name to Ember.removeListener", !!obj && !!eventName); if (!method && "function" === typeof target) { method = target; target = null; } function _removeListener(target, method) { var actions = actionsFor(obj, eventName); var actionIndex = indexOf(actions, target, method); // action doesn't exist, give up silently if (actionIndex === -1) { return; } actions.splice(actionIndex, 3); if ("function" === typeof obj.didRemoveListener) { obj.didRemoveListener(eventName, target, method); } } if (method) { _removeListener(target, method); } else { var meta = obj["__ember_meta__"]; var actions = meta && meta.listeners && meta.listeners[eventName]; if (!actions) { return; } for (var i = actions.length - 3; i >= 0; i -= 3) { _removeListener(actions[i], actions[i + 1]); } } } /** Suspend listener during callback. This should only be used by the target of the event listener when it is taking an action that would cause the event, e.g. an object might suspend its property change listener while it is setting that property. @method suspendListener @for Ember @private @param obj @param {String} eventName @param {Object|Function} target A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @param {Function} callback */ function suspendListener(obj, eventName, target, method, callback) { if (!method && "function" === typeof target) { method = target; target = null; } var actions = actionsFor(obj, eventName); var actionIndex = indexOf(actions, target, method); if (actionIndex !== -1) { actions[actionIndex + 2] |= SUSPENDED; // mark the action as suspended } function tryable() { return callback.call(target); } function finalizer() { if (actionIndex !== -1) { actions[actionIndex + 2] &= ~SUSPENDED; } } return utils.tryFinally(tryable, finalizer); } /** Suspends multiple listeners during a callback. @method suspendListeners @for Ember @private @param obj @param {Array} eventNames Array of event names @param {Object|Function} target A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @param {Function} callback */ function suspendListeners(obj, eventNames, target, method, callback) { if (!method && "function" === typeof target) { method = target; target = null; } var suspendedActions = []; var actionsList = []; var eventName, actions, i, l; for (i = 0, l = eventNames.length; i < l; i++) { eventName = eventNames[i]; actions = actionsFor(obj, eventName); var actionIndex = indexOf(actions, target, method); if (actionIndex !== -1) { actions[actionIndex + 2] |= SUSPENDED; suspendedActions.push(actionIndex); actionsList.push(actions); } } function tryable() { return callback.call(target); } function finalizer() { for (var i = 0, l = suspendedActions.length; i < l; i++) { var actionIndex = suspendedActions[i]; actionsList[i][actionIndex + 2] &= ~SUSPENDED; } } return utils.tryFinally(tryable, finalizer); } /** Return a list of currently watched events @private @method watchedEvents @for Ember @param obj */ function watchedEvents(obj) { var listeners = obj["__ember_meta__"].listeners; var ret = []; if (listeners) { for (var eventName in listeners) { if (eventName !== "__source__" && listeners[eventName]) { ret.push(eventName); } } } return ret; } /** Send an event. The execution of suspended listeners is skipped, and once listeners are removed. A listener without a target is executed on the passed object. If an array of actions is not passed, the actions stored on the passed object are invoked. @method sendEvent @for Ember @param obj @param {String} eventName @param {Array} params Optional parameters for each listener. @param {Array} actions Optional array of actions (listeners). @return true */ function sendEvent(obj, eventName, params, actions) { // first give object a chance to handle it if (obj !== Ember['default'] && "function" === typeof obj.sendEvent) { obj.sendEvent(eventName, params); } if (!actions) { var meta = obj["__ember_meta__"]; actions = meta && meta.listeners && meta.listeners[eventName]; } if (!actions) { return; } for (var i = actions.length - 3; i >= 0; i -= 3) { // looping in reverse for once listeners var target = actions[i]; var method = actions[i + 1]; var flags = actions[i + 2]; if (!method) { continue; } if (flags & SUSPENDED) { continue; } if (flags & ONCE) { removeListener(obj, eventName, target, method); } if (!target) { target = obj; } if ("string" === typeof method) { if (params) { utils.applyStr(target, method, params); } else { target[method](); } } else { if (params) { utils.apply(target, method, params); } else { method.call(target); } } } return true; } /** @private @method hasListeners @for Ember @param obj @param {String} eventName */ function hasListeners(obj, eventName) { var meta = obj["__ember_meta__"]; var actions = meta && meta.listeners && meta.listeners[eventName]; return !!(actions && actions.length); } /** @private @method listenersFor @for Ember @param obj @param {String} eventName */ function listenersFor(obj, eventName) { var ret = []; var meta = obj["__ember_meta__"]; var actions = meta && meta.listeners && meta.listeners[eventName]; if (!actions) { return ret; } for (var i = 0, l = actions.length; i < l; i += 3) { var target = actions[i]; var method = actions[i + 1]; ret.push([target, method]); } return ret; } /** Define a property as a function that should be executed when a specified event or events are triggered. ``` javascript var Job = Ember.Object.extend({ logCompleted: Ember.on('completed', function() { console.log('Job completed!'); }) }); var job = Job.create(); Ember.sendEvent(job, 'completed'); // Logs 'Job completed!' ``` @method on @for Ember @param {String} eventNames* @param {Function} func @return func */ function on() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var func = args.pop(); var events = args; func.__ember_listens__ = events; return func; } }); enifed('ember-metal/expand_properties', ['exports', 'ember-metal/error', 'ember-metal/array'], function (exports, EmberError, array) { 'use strict'; exports['default'] = expandProperties; var SPLIT_REGEX = /\{|\}/; /** Expands `pattern`, invoking `callback` for each expansion. The only pattern supported is brace-expansion, anything else will be passed once to `callback` directly. Example ```js function echo(arg){ console.log(arg); } Ember.expandProperties('foo.bar', echo); //=> 'foo.bar' Ember.expandProperties('{foo,bar}', echo); //=> 'foo', 'bar' Ember.expandProperties('foo.{bar,baz}', echo); //=> 'foo.bar', 'foo.baz' Ember.expandProperties('{foo,bar}.baz', echo); //=> 'foo.baz', 'bar.baz' Ember.expandProperties('foo.{bar,baz}.@each', echo) //=> 'foo.bar.@each', 'foo.baz.@each' Ember.expandProperties('{foo,bar}.{spam,eggs}', echo) //=> 'foo.spam', 'foo.eggs', 'bar.spam', 'bar.eggs' Ember.expandProperties('{foo}.bar.{baz}') //=> 'foo.bar.baz' ``` @method @private @param {String} pattern The property pattern to expand. @param {Function} callback The callback to invoke. It is invoked once per expansion, and is passed the expansion. */ function expandProperties(pattern, callback) { if (pattern.indexOf(' ') > -1) { throw new EmberError['default']('Brace expanded properties cannot contain spaces, e.g. \'user.{firstName, lastName}\' should be \'user.{firstName,lastName}\''); } if ('string' === typeof pattern) { var parts = pattern.split(SPLIT_REGEX); var properties = [parts]; array.forEach.call(parts, function (part, index) { if (part.indexOf(',') >= 0) { properties = duplicateAndReplace(properties, part.split(','), index); } }); array.forEach.call(properties, function (property) { callback(property.join('')); }); } else { callback(pattern); } } function duplicateAndReplace(properties, currentParts, index) { var all = []; array.forEach.call(properties, function (property) { array.forEach.call(currentParts, function (part) { var current = property.slice(0); current[index] = part; all.push(current); }); }); return all; } }); enifed('ember-metal/get_properties', ['exports', 'ember-metal/property_get', 'ember-metal/utils'], function (exports, property_get, utils) { 'use strict'; exports['default'] = getProperties; function getProperties(obj) { var ret = {}; var propertyNames = arguments; var i = 1; if (arguments.length === 2 && utils.isArray(arguments[1])) { i = 0; propertyNames = arguments[1]; } for (var len = propertyNames.length; i < len; i++) { ret[propertyNames[i]] = property_get.get(obj, propertyNames[i]); } return ret; } }); enifed('ember-metal/injected_property', ['exports', 'ember-metal/core', 'ember-metal/computed', 'ember-metal/alias', 'ember-metal/properties', 'ember-metal/platform/create'], function (exports, Ember, computed, alias, properties, create) { 'use strict'; function InjectedProperty(type, name) { this.type = type; this.name = name; this._super$Constructor(injectedPropertyGet); AliasedPropertyPrototype.oneWay.call(this); } function injectedPropertyGet(keyName) { var possibleDesc = this[keyName]; var desc = possibleDesc !== null && typeof possibleDesc === "object" && possibleDesc.isDescriptor ? possibleDesc : undefined; Ember['default'].assert("Attempting to lookup an injected property on an object without a container, ensure that the object was instantiated via a container.", this.container); return this.container.lookup(desc.type + ":" + (desc.name || keyName)); } InjectedProperty.prototype = create['default'](properties.Descriptor.prototype); var InjectedPropertyPrototype = InjectedProperty.prototype; var ComputedPropertyPrototype = computed.ComputedProperty.prototype; var AliasedPropertyPrototype = alias.AliasedProperty.prototype; InjectedPropertyPrototype._super$Constructor = computed.ComputedProperty; InjectedPropertyPrototype.get = ComputedPropertyPrototype.get; InjectedPropertyPrototype.readOnly = ComputedPropertyPrototype.readOnly; InjectedPropertyPrototype.teardown = ComputedPropertyPrototype.teardown; exports['default'] = InjectedProperty; }); enifed('ember-metal/instrumentation', ['exports', 'ember-metal/core', 'ember-metal/utils'], function (exports, Ember, utils) { 'use strict'; exports.instrument = instrument; exports._instrumentStart = _instrumentStart; exports.subscribe = subscribe; exports.unsubscribe = unsubscribe; exports.reset = reset; var subscribers = []; var cache = {}; var populateListeners = function (name) { var listeners = []; var subscriber; for (var i = 0, l = subscribers.length; i < l; i++) { subscriber = subscribers[i]; if (subscriber.regex.test(name)) { listeners.push(subscriber.object); } } cache[name] = listeners; return listeners; }; var time = (function () { var perf = "undefined" !== typeof window ? window.performance || {} : {}; var fn = perf.now || perf.mozNow || perf.webkitNow || perf.msNow || perf.oNow; // fn.bind will be available in all the browsers that support the advanced window.performance... ;-) return fn ? fn.bind(perf) : function () { return +new Date(); }; })(); /** Notifies event's subscribers, calls `before` and `after` hooks. @method instrument @namespace Ember.Instrumentation @param {String} [name] Namespaced event name. @param {Object} payload @param {Function} callback Function that you're instrumenting. @param {Object} binding Context that instrument function is called with. */ function instrument(name, _payload, callback, binding) { if (arguments.length <= 3 && typeof _payload === "function") { binding = callback; callback = _payload; _payload = undefined; } if (subscribers.length === 0) { return callback.call(binding); } var payload = _payload || {}; var finalizer = _instrumentStart(name, function () { return payload; }); if (finalizer) { var tryable = function _instrumenTryable() { return callback.call(binding); }; var catchable = function _instrumentCatchable(e) { payload.exception = e; }; return utils.tryCatchFinally(tryable, catchable, finalizer); } else { return callback.call(binding); } } // private for now function _instrumentStart(name, _payload) { var listeners = cache[name]; if (!listeners) { listeners = populateListeners(name); } if (listeners.length === 0) { return; } var payload = _payload(); var STRUCTURED_PROFILE = Ember['default'].STRUCTURED_PROFILE; var timeName; if (STRUCTURED_PROFILE) { timeName = name + ": " + payload.object; console.time(timeName); } var l = listeners.length; var beforeValues = new Array(l); var i, listener; var timestamp = time(); for (i = 0; i < l; i++) { listener = listeners[i]; beforeValues[i] = listener.before(name, timestamp, payload); } return function _instrumentEnd() { var i, l, listener; var timestamp = time(); for (i = 0, l = listeners.length; i < l; i++) { listener = listeners[i]; listener.after(name, timestamp, payload, beforeValues[i]); } if (STRUCTURED_PROFILE) { console.timeEnd(timeName); } }; } /** Subscribes to a particular event or instrumented block of code. @method subscribe @namespace Ember.Instrumentation @param {String} [pattern] Namespaced event name. @param {Object} [object] Before and After hooks. @return {Subscriber} */ function subscribe(pattern, object) { var paths = pattern.split("."); var path; var regex = []; for (var i = 0, l = paths.length; i < l; i++) { path = paths[i]; if (path === "*") { regex.push("[^\\.]*"); } else { regex.push(path); } } regex = regex.join("\\."); regex = regex + "(\\..*)?"; var subscriber = { pattern: pattern, regex: new RegExp("^" + regex + "$"), object: object }; subscribers.push(subscriber); cache = {}; return subscriber; } /** Unsubscribes from a particular event or instrumented block of code. @method unsubscribe @namespace Ember.Instrumentation @param {Object} [subscriber] */ function unsubscribe(subscriber) { var index; for (var i = 0, l = subscribers.length; i < l; i++) { if (subscribers[i] === subscriber) { index = i; } } subscribers.splice(index, 1); cache = {}; } /** Resets `Ember.Instrumentation` by flushing list of subscribers. @method reset @namespace Ember.Instrumentation */ function reset() { subscribers.length = 0; cache = {}; } exports.subscribers = subscribers; }); enifed('ember-metal/is_blank', ['exports', 'ember-metal/is_empty'], function (exports, isEmpty) { 'use strict'; exports['default'] = isBlank; function isBlank(obj) { return isEmpty['default'](obj) || typeof obj === 'string' && obj.match(/\S/) === null; } }); enifed('ember-metal/is_empty', ['exports', 'ember-metal/property_get', 'ember-metal/is_none'], function (exports, property_get, isNone) { 'use strict'; function isEmpty(obj) { var none = isNone['default'](obj); if (none) { return none; } if (typeof obj.size === 'number') { return !obj.size; } var objectType = typeof obj; if (objectType === 'object') { var size = property_get.get(obj, 'size'); if (typeof size === 'number') { return !size; } } if (typeof obj.length === 'number' && objectType !== 'function') { return !obj.length; } if (objectType === 'object') { var length = property_get.get(obj, 'length'); if (typeof length === 'number') { return !length; } } return false; } exports['default'] = isEmpty; }); enifed('ember-metal/is_none', ['exports'], function (exports) { 'use strict'; /** Returns true if the passed value is null or undefined. This avoids errors from JSLint complaining about use of ==, which can be technically confusing. ```javascript Ember.isNone(); // true Ember.isNone(null); // true Ember.isNone(undefined); // true Ember.isNone(''); // false Ember.isNone([]); // false Ember.isNone(function() {}); // false ``` @method isNone @for Ember @param {Object} obj Value to test @return {Boolean} */ function isNone(obj) { return obj === null || obj === undefined; } exports['default'] = isNone; }); enifed('ember-metal/is_present', ['exports', 'ember-metal/is_blank'], function (exports, isBlank) { 'use strict'; exports['default'] = isPresent; function isPresent(obj) { return !isBlank['default'](obj); } }); enifed('ember-metal/keys', ['exports', 'ember-metal/platform/define_property'], function (exports, define_property) { 'use strict'; var keys = Object.keys; if (!keys || !define_property.canDefineNonEnumerableProperties) { // modified from // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys keys = (function () { var hasOwnProperty = Object.prototype.hasOwnProperty; var hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'); var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor']; var dontEnumsLength = dontEnums.length; return function keys(obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = []; var prop, i; for (prop in obj) { if (prop !== '_super' && prop.lastIndexOf('__', 0) !== 0 && hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; })(); } exports['default'] = keys; }); enifed('ember-metal/libraries', ['exports', 'ember-metal/core', 'ember-metal/enumerable_utils'], function (exports, Ember, enumerable_utils) { 'use strict'; function Libraries() { this._registry = []; this._coreLibIndex = 0; } Libraries.prototype = { constructor: Libraries, _getLibraryByName: function (name) { var libs = this._registry; var count = libs.length; for (var i = 0; i < count; i++) { if (libs[i].name === name) { return libs[i]; } } }, register: function (name, version, isCoreLibrary) { var index = this._registry.length; if (!this._getLibraryByName(name)) { if (isCoreLibrary) { index = this._coreLibIndex++; } this._registry.splice(index, 0, { name: name, version: version }); } else { Ember['default'].warn("Library \"" + name + "\" is already registered with Ember."); } }, registerCoreLibrary: function (name, version) { this.register(name, version, true); }, deRegister: function (name) { var lib = this._getLibraryByName(name); var index; if (lib) { index = enumerable_utils.indexOf(this._registry, lib); this._registry.splice(index, 1); } }, each: function (callback) { Ember['default'].deprecate("Using Ember.libraries.each() is deprecated. Access to a list of registered libraries is currently a private API. If you are not knowingly accessing this method, your out-of-date Ember Inspector may be doing so."); enumerable_utils.forEach(this._registry, function (lib) { callback(lib.name, lib.version); }); } }; exports['default'] = Libraries; }); enifed('ember-metal/logger', ['exports', 'ember-metal/core', 'ember-metal/error'], function (exports, Ember, EmberError) { 'use strict'; function K() { return this; } function consoleMethod(name) { var consoleObj, logToConsole; if (Ember['default'].imports.console) { consoleObj = Ember['default'].imports.console; } else if (typeof console !== "undefined") { consoleObj = console; } var method = typeof consoleObj === "object" ? consoleObj[name] : null; if (method) { // Older IE doesn't support bind, but Chrome needs it if (typeof method.bind === "function") { logToConsole = method.bind(consoleObj); logToConsole.displayName = "console." + name; return logToConsole; } else if (typeof method.apply === "function") { logToConsole = function () { method.apply(consoleObj, arguments); }; logToConsole.displayName = "console." + name; return logToConsole; } else { return function () { var message = Array.prototype.join.call(arguments, ", "); method(message); }; } } } function assertPolyfill(test, message) { if (!test) { try { // attempt to preserve the stack throw new EmberError['default']("assertion failed: " + message); } catch (error) { setTimeout(function () { throw error; }, 0); } } } /** Inside Ember-Metal, simply uses the methods from `imports.console`. Override this to provide more robust logging functionality. @class Logger @namespace Ember */ exports['default'] = { /** Logs the arguments to the console. You can pass as many arguments as you want and they will be joined together with a space. ```javascript var foo = 1; Ember.Logger.log('log value of foo:', foo); // "log value of foo: 1" will be printed to the console ``` @method log @for Ember.Logger @param {*} arguments */ log: consoleMethod("log") || K, /** Prints the arguments to the console with a warning icon. You can pass as many arguments as you want and they will be joined together with a space. ```javascript Ember.Logger.warn('Something happened!'); // "Something happened!" will be printed to the console with a warning icon. ``` @method warn @for Ember.Logger @param {*} arguments */ warn: consoleMethod("warn") || K, /** Prints the arguments to the console with an error icon, red text and a stack trace. You can pass as many arguments as you want and they will be joined together with a space. ```javascript Ember.Logger.error('Danger! Danger!'); // "Danger! Danger!" will be printed to the console in red text. ``` @method error @for Ember.Logger @param {*} arguments */ error: consoleMethod("error") || K, /** Logs the arguments to the console. You can pass as many arguments as you want and they will be joined together with a space. ```javascript var foo = 1; Ember.Logger.info('log value of foo:', foo); // "log value of foo: 1" will be printed to the console ``` @method info @for Ember.Logger @param {*} arguments */ info: consoleMethod("info") || K, /** Logs the arguments to the console in blue text. You can pass as many arguments as you want and they will be joined together with a space. ```javascript var foo = 1; Ember.Logger.debug('log value of foo:', foo); // "log value of foo: 1" will be printed to the console ``` @method debug @for Ember.Logger @param {*} arguments */ debug: consoleMethod("debug") || consoleMethod("info") || K, /** If the value passed into `Ember.Logger.assert` is not truthy it will throw an error with a stack trace. ```javascript Ember.Logger.assert(true); // undefined Ember.Logger.assert(true === false); // Throws an Assertion failed error. ``` @method assert @for Ember.Logger @param {Boolean} bool Value to test */ assert: consoleMethod("assert") || assertPolyfill }; }); enifed('ember-metal/map', ['exports', 'ember-metal/utils', 'ember-metal/array', 'ember-metal/platform/create', 'ember-metal/deprecate_property'], function (exports, utils, array, create, deprecate_property) { 'use strict'; exports.OrderedSet = OrderedSet; exports.Map = Map; exports.MapWithDefault = MapWithDefault; /** @module ember-metal */ /* JavaScript (before ES6) does not have a Map implementation. Objects, which are often used as dictionaries, may only have Strings as keys. Because Ember has a way to get a unique identifier for every object via `Ember.guidFor`, we can implement a performant Map with arbitrary keys. Because it is commonly used in low-level bookkeeping, Map is implemented as a pure JavaScript object for performance. This implementation follows the current iteration of the ES6 proposal for maps (http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets), with one exception: as we do not have the luxury of in-VM iteration, we implement a forEach method for iteration. Map is mocked out to look like an Ember object, so you can do `Ember.Map.create()` for symmetry with other Ember classes. */ function missingFunction(fn) { throw new TypeError("" + Object.prototype.toString.call(fn) + " is not a function"); } function missingNew(name) { throw new TypeError("Constructor " + name + " requires 'new'"); } function copyNull(obj) { var output = create['default'](null); for (var prop in obj) { // hasOwnPropery is not needed because obj is Object.create(null); output[prop] = obj[prop]; } return output; } function copyMap(original, newObject) { var keys = original._keys.copy(); var values = copyNull(original._values); newObject._keys = keys; newObject._values = values; newObject.size = original.size; return newObject; } /** This class is used internally by Ember and Ember Data. Please do not use it at this time. We plan to clean it up and add many tests soon. @class OrderedSet @namespace Ember @constructor @private */ function OrderedSet() { if (this instanceof OrderedSet) { this.clear(); this._silenceRemoveDeprecation = false; } else { missingNew("OrderedSet"); } } /** @method create @static @return {Ember.OrderedSet} */ OrderedSet.create = function () { var Constructor = this; return new Constructor(); }; OrderedSet.prototype = { constructor: OrderedSet, /** @method clear */ clear: function () { this.presenceSet = create['default'](null); this.list = []; this.size = 0; }, /** @method add @param obj @param guid (optional, and for internal use) @return {Ember.OrderedSet} */ add: function (obj, _guid) { var guid = _guid || utils.guidFor(obj); var presenceSet = this.presenceSet; var list = this.list; if (presenceSet[guid] !== true) { presenceSet[guid] = true; this.size = list.push(obj); } return this; }, /** @deprecated @method remove @param obj @param _guid (optional and for internal use only) @return {Boolean} */ remove: function (obj, _guid) { Ember.deprecate("Calling `OrderedSet.prototype.remove` has been deprecated, please use `OrderedSet.prototype.delete` instead.", this._silenceRemoveDeprecation); return this["delete"](obj, _guid); }, /** @since 1.8.0 @method delete @param obj @param _guid (optional and for internal use only) @return {Boolean} */ "delete": function (obj, _guid) { var guid = _guid || utils.guidFor(obj); var presenceSet = this.presenceSet; var list = this.list; if (presenceSet[guid] === true) { delete presenceSet[guid]; var index = array.indexOf.call(list, obj); if (index > -1) { list.splice(index, 1); } this.size = list.length; return true; } else { return false; } }, /** @method isEmpty @return {Boolean} */ isEmpty: function () { return this.size === 0; }, /** @method has @param obj @return {Boolean} */ has: function (obj) { if (this.size === 0) { return false; } var guid = utils.guidFor(obj); var presenceSet = this.presenceSet; return presenceSet[guid] === true; }, /** @method forEach @param {Function} fn @param self */ forEach: function (fn /*, ...thisArg*/) { if (typeof fn !== "function") { missingFunction(fn); } if (this.size === 0) { return; } var list = this.list; var length = arguments.length; var i; if (length === 2) { for (i = 0; i < list.length; i++) { fn.call(arguments[1], list[i]); } } else { for (i = 0; i < list.length; i++) { fn(list[i]); } } }, /** @method toArray @return {Array} */ toArray: function () { return this.list.slice(); }, /** @method copy @return {Ember.OrderedSet} */ copy: function () { var Constructor = this.constructor; var set = new Constructor(); set._silenceRemoveDeprecation = this._silenceRemoveDeprecation; set.presenceSet = copyNull(this.presenceSet); set.list = this.toArray(); set.size = this.size; return set; } }; deprecate_property.deprecateProperty(OrderedSet.prototype, "length", "size"); /** A Map stores values indexed by keys. Unlike JavaScript's default Objects, the keys of a Map can be any JavaScript object. Internally, a Map has two data structures: 1. `keys`: an OrderedSet of all of the existing keys 2. `values`: a JavaScript Object indexed by the `Ember.guidFor(key)` When a key/value pair is added for the first time, we add the key to the `keys` OrderedSet, and create or replace an entry in `values`. When an entry is deleted, we delete its entry in `keys` and `values`. @class Map @namespace Ember @private @constructor */ function Map() { if (this instanceof this.constructor) { this._keys = OrderedSet.create(); this._keys._silenceRemoveDeprecation = true; this._values = create['default'](null); this.size = 0; } else { missingNew("OrderedSet"); } } Ember.Map = Map; /** @method create @static */ Map.create = function () { var Constructor = this; return new Constructor(); }; Map.prototype = { constructor: Map, /** This property will change as the number of objects in the map changes. @since 1.8.0 @property size @type number @default 0 */ size: 0, /** Retrieve the value associated with a given key. @method get @param {*} key @return {*} the value associated with the key, or `undefined` */ get: function (key) { if (this.size === 0) { return; } var values = this._values; var guid = utils.guidFor(key); return values[guid]; }, /** Adds a value to the map. If a value for the given key has already been provided, the new value will replace the old value. @method set @param {*} key @param {*} value @return {Ember.Map} */ set: function (key, value) { var keys = this._keys; var values = this._values; var guid = utils.guidFor(key); // ensure we don't store -0 var k = key === -0 ? 0 : key; keys.add(k, guid); values[guid] = value; this.size = keys.size; return this; }, /** @deprecated see delete Removes a value from the map for an associated key. @method remove @param {*} key @return {Boolean} true if an item was removed, false otherwise */ remove: function (key) { Ember.deprecate("Calling `Map.prototype.remove` has been deprecated, please use `Map.prototype.delete` instead."); return this["delete"](key); }, /** Removes a value from the map for an associated key. @since 1.8.0 @method delete @param {*} key @return {Boolean} true if an item was removed, false otherwise */ "delete": function (key) { if (this.size === 0) { return false; } // don't use ES6 "delete" because it will be annoying // to use in browsers that are not ES6 friendly; var keys = this._keys; var values = this._values; var guid = utils.guidFor(key); if (keys["delete"](key, guid)) { delete values[guid]; this.size = keys.size; return true; } else { return false; } }, /** Check whether a key is present. @method has @param {*} key @return {Boolean} true if the item was present, false otherwise */ has: function (key) { return this._keys.has(key); }, /** Iterate over all the keys and values. Calls the function once for each key, passing in value, key, and the map being iterated over, in that order. The keys are guaranteed to be iterated over in insertion order. @method forEach @param {Function} callback @param {*} self if passed, the `this` value inside the callback. By default, `this` is the map. */ forEach: function (callback /*, ...thisArg*/) { if (typeof callback !== "function") { missingFunction(callback); } if (this.size === 0) { return; } var length = arguments.length; var map = this; var cb, thisArg; if (length === 2) { thisArg = arguments[1]; cb = function (key) { callback.call(thisArg, map.get(key), key, map); }; } else { cb = function (key) { callback(map.get(key), key, map); }; } this._keys.forEach(cb); }, /** @method clear */ clear: function () { this._keys.clear(); this._values = create['default'](null); this.size = 0; }, /** @method copy @return {Ember.Map} */ copy: function () { return copyMap(this, new Map()); } }; deprecate_property.deprecateProperty(Map.prototype, "length", "size"); /** @class MapWithDefault @namespace Ember @extends Ember.Map @private @constructor @param [options] @param {*} [options.defaultValue] */ function MapWithDefault(options) { this._super$constructor(); this.defaultValue = options.defaultValue; } /** @method create @static @param [options] @param {*} [options.defaultValue] @return {Ember.MapWithDefault|Ember.Map} If options are passed, returns `Ember.MapWithDefault` otherwise returns `Ember.Map` */ MapWithDefault.create = function (options) { if (options) { return new MapWithDefault(options); } else { return new Map(); } }; MapWithDefault.prototype = create['default'](Map.prototype); MapWithDefault.prototype.constructor = MapWithDefault; MapWithDefault.prototype._super$constructor = Map; MapWithDefault.prototype._super$get = Map.prototype.get; /** Retrieve the value associated with a given key. @method get @param {*} key @return {*} the value associated with the key, or the default value */ MapWithDefault.prototype.get = function (key) { var hasValue = this.has(key); if (hasValue) { return this._super$get(key); } else { var defaultValue = this.defaultValue(key); this.set(key, defaultValue); return defaultValue; } }; /** @method copy @return {Ember.MapWithDefault} */ MapWithDefault.prototype.copy = function () { var Constructor = this.constructor; return copyMap(this, new Constructor({ defaultValue: this.defaultValue })); }; exports['default'] = Map; }); enifed('ember-metal/merge', ['exports', 'ember-metal/keys'], function (exports, keys) { 'use strict'; exports.assign = assign; exports['default'] = merge; function merge(original, updates) { if (!updates || typeof updates !== 'object') { return original; } var props = keys['default'](updates); var prop; var length = props.length; for (var i = 0; i < length; i++) { prop = props[i]; original[prop] = updates[prop]; } return original; } function assign(original) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } for (var i = 0, l = args.length; i < l; i++) { var arg = args[i]; if (!arg) { continue; } for (var prop in arg) { if (arg.hasOwnProperty(prop)) { original[prop] = arg[prop]; } } } return original; } }); enifed('ember-metal/mixin', ['exports', 'ember-metal/core', 'ember-metal/merge', 'ember-metal/array', 'ember-metal/platform/create', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/utils', 'ember-metal/expand_properties', 'ember-metal/properties', 'ember-metal/computed', 'ember-metal/binding', 'ember-metal/observer', 'ember-metal/events', 'ember-metal/streams/utils'], function (exports, Ember, merge, array, o_create, property_get, property_set, utils, expandProperties, ember_metal__properties, computed, ember_metal__binding, ember_metal__observer, events, streams__utils) { exports.mixin = mixin; exports.required = required; exports.aliasMethod = aliasMethod; exports.observer = observer; exports.immediateObserver = immediateObserver; exports.beforeObserver = beforeObserver; exports.Mixin = Mixin; "REMOVE_USE_STRICT: true";var REQUIRED; var a_slice = [].slice; function superFunction() { var func = this.__nextSuper; var ret; if (func) { var length = arguments.length; this.__nextSuper = null; if (length === 0) { ret = func.call(this); } else if (length === 1) { ret = func.call(this, arguments[0]); } else if (length === 2) { ret = func.call(this, arguments[0], arguments[1]); } else { ret = func.apply(this, arguments); } this.__nextSuper = func; return ret; } } // ensure we prime superFunction to mitigate // v8 bug potentially incorrectly deopts this function: https://code.google.com/p/v8/issues/detail?id=3709 var primer = { __nextSuper: function (a, b, c, d) {} }; superFunction.call(primer); superFunction.call(primer, 1); superFunction.call(primer, 1, 2); superFunction.call(primer, 1, 2, 3); function mixinsMeta(obj) { var m = utils.meta(obj, true); var ret = m.mixins; if (!ret) { ret = m.mixins = {}; } else if (!m.hasOwnProperty("mixins")) { ret = m.mixins = o_create['default'](ret); } return ret; } function isMethod(obj) { return "function" === typeof obj && obj.isMethod !== false && obj !== Boolean && obj !== Object && obj !== Number && obj !== Array && obj !== Date && obj !== String; } var CONTINUE = {}; function mixinProperties(mixinsMeta, mixin) { var guid; if (mixin instanceof Mixin) { guid = utils.guidFor(mixin); if (mixinsMeta[guid]) { return CONTINUE; } mixinsMeta[guid] = mixin; return mixin.properties; } else { return mixin; // apply anonymous mixin properties } } function concatenatedMixinProperties(concatProp, props, values, base) { var concats; // reset before adding each new mixin to pickup concats from previous concats = values[concatProp] || base[concatProp]; if (props[concatProp]) { concats = concats ? concats.concat(props[concatProp]) : props[concatProp]; } return concats; } function giveDescriptorSuper(meta, key, property, values, descs, base) { var superProperty; // Computed properties override methods, and do not call super to them if (values[key] === undefined) { // Find the original descriptor in a parent mixin superProperty = descs[key]; } // If we didn't find the original descriptor in a parent mixin, find // it on the original object. if (!superProperty) { var possibleDesc = base[key]; var superDesc = possibleDesc !== null && typeof possibleDesc === "object" && possibleDesc.isDescriptor ? possibleDesc : undefined; superProperty = superDesc; } if (superProperty === undefined || !(superProperty instanceof computed.ComputedProperty)) { return property; } // Since multiple mixins may inherit from the same parent, we need // to clone the computed property so that other mixins do not receive // the wrapped version. property = o_create['default'](property); property._getter = utils.wrap(property._getter, superProperty._getter); if (superProperty._setter) { if (property._setter) { property._setter = utils.wrap(property._setter, superProperty._setter); } else { property._setter = superProperty._setter; } } return property; } var sourceAvailable = (function () { return this; }).toString().indexOf("return this;") > -1; function giveMethodSuper(obj, key, method, values, descs) { var superMethod; // Methods overwrite computed properties, and do not call super to them. if (descs[key] === undefined) { // Find the original method in a parent mixin superMethod = values[key]; } // If we didn't find the original value in a parent mixin, find it in // the original object superMethod = superMethod || obj[key]; // Only wrap the new method if the original method was a function if (superMethod === undefined || "function" !== typeof superMethod) { return method; } var hasSuper; if (sourceAvailable) { hasSuper = method.__hasSuper; if (hasSuper === undefined) { hasSuper = method.toString().indexOf("_super") > -1; method.__hasSuper = hasSuper; } } if (sourceAvailable === false || hasSuper) { return utils.wrap(method, superMethod); } else { return method; } } function applyConcatenatedProperties(obj, key, value, values) { var baseValue = values[key] || obj[key]; if (baseValue) { if ("function" === typeof baseValue.concat) { if (value === null || value === undefined) { return baseValue; } else { return baseValue.concat(value); } } else { return utils.makeArray(baseValue).concat(value); } } else { return utils.makeArray(value); } } function applyMergedProperties(obj, key, value, values) { var baseValue = values[key] || obj[key]; Ember['default'].assert("You passed in `" + JSON.stringify(value) + "` as the value for `" + key + "` but `" + key + "` cannot be an Array", !utils.isArray(value)); if (!baseValue) { return value; } var newBase = merge['default']({}, baseValue); var hasFunction = false; for (var prop in value) { if (!value.hasOwnProperty(prop)) { continue; } var propValue = value[prop]; if (isMethod(propValue)) { // TODO: support for Computed Properties, etc? hasFunction = true; newBase[prop] = giveMethodSuper(obj, prop, propValue, baseValue, {}); } else { newBase[prop] = propValue; } } if (hasFunction) { newBase._super = superFunction; } return newBase; } function addNormalizedProperty(base, key, value, meta, descs, values, concats, mergings) { if (value instanceof ember_metal__properties.Descriptor) { if (value === REQUIRED && descs[key]) { return CONTINUE; } // Wrap descriptor function to implement // __nextSuper() if needed if (value._getter) { value = giveDescriptorSuper(meta, key, value, values, descs, base); } descs[key] = value; values[key] = undefined; } else { if (concats && array.indexOf.call(concats, key) >= 0 || key === "concatenatedProperties" || key === "mergedProperties") { value = applyConcatenatedProperties(base, key, value, values); } else if (mergings && array.indexOf.call(mergings, key) >= 0) { value = applyMergedProperties(base, key, value, values); } else if (isMethod(value)) { value = giveMethodSuper(base, key, value, values, descs); } descs[key] = undefined; values[key] = value; } } function mergeMixins(mixins, m, descs, values, base, keys) { var currentMixin, props, key, concats, mergings, meta; function removeKeys(keyName) { delete descs[keyName]; delete values[keyName]; } for (var i = 0, l = mixins.length; i < l; i++) { currentMixin = mixins[i]; Ember['default'].assert("Expected hash or Mixin instance, got " + Object.prototype.toString.call(currentMixin), typeof currentMixin === "object" && currentMixin !== null && Object.prototype.toString.call(currentMixin) !== "[object Array]"); props = mixinProperties(m, currentMixin); if (props === CONTINUE) { continue; } if (props) { meta = utils.meta(base); if (base.willMergeMixin) { base.willMergeMixin(props); } concats = concatenatedMixinProperties("concatenatedProperties", props, values, base); mergings = concatenatedMixinProperties("mergedProperties", props, values, base); for (key in props) { if (!props.hasOwnProperty(key)) { continue; } keys.push(key); addNormalizedProperty(base, key, props[key], meta, descs, values, concats, mergings); } // manually copy toString() because some JS engines do not enumerate it if (props.hasOwnProperty("toString")) { base.toString = props.toString; } } else if (currentMixin.mixins) { mergeMixins(currentMixin.mixins, m, descs, values, base, keys); if (currentMixin._without) { array.forEach.call(currentMixin._without, removeKeys); } } } } var IS_BINDING = /^.+Binding$/; function detectBinding(obj, key, value, m) { if (IS_BINDING.test(key)) { var bindings = m.bindings; if (!bindings) { bindings = m.bindings = {}; } else if (!m.hasOwnProperty("bindings")) { bindings = m.bindings = o_create['default'](m.bindings); } bindings[key] = value; } } function connectStreamBinding(obj, key, stream) { var onNotify = function (stream) { ember_metal__observer._suspendObserver(obj, key, null, didChange, function () { property_set.trySet(obj, key, stream.value()); }); }; var didChange = function () { stream.setValue(property_get.get(obj, key), onNotify); }; // Initialize value property_set.set(obj, key, stream.value()); ember_metal__observer.addObserver(obj, key, null, didChange); stream.subscribe(onNotify); if (obj._streamBindingSubscriptions === undefined) { obj._streamBindingSubscriptions = o_create['default'](null); } obj._streamBindingSubscriptions[key] = onNotify; } function connectBindings(obj, m) { // TODO Mixin.apply(instance) should disconnect binding if exists var bindings = m.bindings; var key, binding, to; if (bindings) { for (key in bindings) { binding = bindings[key]; if (binding) { to = key.slice(0, -7); // strip Binding off end if (streams__utils.isStream(binding)) { connectStreamBinding(obj, to, binding); continue; } else if (binding instanceof ember_metal__binding.Binding) { binding = binding.copy(); // copy prototypes' instance binding.to(to); } else { // binding is string path binding = new ember_metal__binding.Binding(to, binding); } binding.connect(obj); obj[key] = binding; } } // mark as applied m.bindings = {}; } } function finishPartial(obj, m) { connectBindings(obj, m || utils.meta(obj)); return obj; } function followAlias(obj, desc, m, descs, values) { var altKey = desc.methodName; var value; var possibleDesc; if (descs[altKey] || values[altKey]) { value = values[altKey]; desc = descs[altKey]; } else if ((possibleDesc = obj[altKey]) && possibleDesc !== null && typeof possibleDesc === "object" && possibleDesc.isDescriptor) { desc = possibleDesc; value = undefined; } else { desc = undefined; value = obj[altKey]; } return { desc: desc, value: value }; } function updateObserversAndListeners(obj, key, observerOrListener, pathsKey, updateMethod) { var paths = observerOrListener[pathsKey]; if (paths) { for (var i = 0, l = paths.length; i < l; i++) { updateMethod(obj, paths[i], null, key); } } } function replaceObserversAndListeners(obj, key, observerOrListener) { var prev = obj[key]; if ("function" === typeof prev) { updateObserversAndListeners(obj, key, prev, "__ember_observesBefore__", ember_metal__observer.removeBeforeObserver); updateObserversAndListeners(obj, key, prev, "__ember_observes__", ember_metal__observer.removeObserver); updateObserversAndListeners(obj, key, prev, "__ember_listens__", events.removeListener); } if ("function" === typeof observerOrListener) { updateObserversAndListeners(obj, key, observerOrListener, "__ember_observesBefore__", ember_metal__observer.addBeforeObserver); updateObserversAndListeners(obj, key, observerOrListener, "__ember_observes__", ember_metal__observer.addObserver); updateObserversAndListeners(obj, key, observerOrListener, "__ember_listens__", events.addListener); } } function applyMixin(obj, mixins, partial) { var descs = {}; var values = {}; var m = utils.meta(obj); var keys = []; var key, value, desc; obj._super = superFunction; // Go through all mixins and hashes passed in, and: // // * Handle concatenated properties // * Handle merged properties // * Set up _super wrapping if necessary // * Set up computed property descriptors // * Copying `toString` in broken browsers mergeMixins(mixins, mixinsMeta(obj), descs, values, obj, keys); for (var i = 0, l = keys.length; i < l; i++) { key = keys[i]; if (key === "constructor" || !values.hasOwnProperty(key)) { continue; } desc = descs[key]; value = values[key]; if (desc === REQUIRED) { continue; } while (desc && desc instanceof Alias) { var followed = followAlias(obj, desc, m, descs, values); desc = followed.desc; value = followed.value; } if (desc === undefined && value === undefined) { continue; } replaceObserversAndListeners(obj, key, value); detectBinding(obj, key, value, m); ember_metal__properties.defineProperty(obj, key, desc, value, m); } if (!partial) { // don't apply to prototype finishPartial(obj, m); } return obj; } /** @method mixin @for Ember @param obj @param mixins* @return obj */ function mixin(obj) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } applyMixin(obj, args, false); return obj; } /** The `Ember.Mixin` class allows you to create mixins, whose properties can be added to other classes. For instance, ```javascript App.Editable = Ember.Mixin.create({ edit: function() { console.log('starting to edit'); this.set('isEditing', true); }, isEditing: false }); // Mix mixins into classes by passing them as the first arguments to // .extend. App.CommentView = Ember.View.extend(App.Editable, { template: Ember.Handlebars.compile('{{#if view.isEditing}}...{{else}}...{{/if}}') }); commentView = App.CommentView.create(); commentView.edit(); // outputs 'starting to edit' ``` Note that Mixins are created with `Ember.Mixin.create`, not `Ember.Mixin.extend`. Note that mixins extend a constructor's prototype so arrays and object literals defined as properties will be shared amongst objects that implement the mixin. If you want to define a property in a mixin that is not shared, you can define it either as a computed property or have it be created on initialization of the object. ```javascript //filters array will be shared amongst any object implementing mixin App.Filterable = Ember.Mixin.create({ filters: Ember.A() }); //filters will be a separate array for every object implementing the mixin App.Filterable = Ember.Mixin.create({ filters: Ember.computed(function() {return Ember.A();}) }); //filters will be created as a separate array during the object's initialization App.Filterable = Ember.Mixin.create({ init: function() { this._super.apply(this, arguments); this.set("filters", Ember.A()); } }); ``` @class Mixin @namespace Ember */ exports['default'] = Mixin; function Mixin(args, properties) { this.properties = properties; var length = args && args.length; if (length > 0) { var m = new Array(length); for (var i = 0; i < length; i++) { var x = args[i]; if (x instanceof Mixin) { m[i] = x; } else { m[i] = new Mixin(undefined, x); } } this.mixins = m; } else { this.mixins = undefined; } this.ownerConstructor = undefined; } Mixin._apply = applyMixin; Mixin.applyPartial = function (obj) { var args = a_slice.call(arguments, 1); return applyMixin(obj, args, true); }; Mixin.finishPartial = finishPartial; // ES6TODO: this relies on a global state? Ember['default'].anyUnprocessedMixins = false; /** @method create @static @param arguments* */ Mixin.create = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } // ES6TODO: this relies on a global state? Ember['default'].anyUnprocessedMixins = true; var M = this; return new M(args, undefined); }; var MixinPrototype = Mixin.prototype; /** @method reopen @param arguments* */ MixinPrototype.reopen = function () { var currentMixin; if (this.properties) { currentMixin = new Mixin(undefined, this.properties); this.properties = undefined; this.mixins = [currentMixin]; } else if (!this.mixins) { this.mixins = []; } var len = arguments.length; var mixins = this.mixins; var idx; for (idx = 0; idx < len; idx++) { currentMixin = arguments[idx]; Ember['default'].assert("Expected hash or Mixin instance, got " + Object.prototype.toString.call(currentMixin), typeof currentMixin === "object" && currentMixin !== null && Object.prototype.toString.call(currentMixin) !== "[object Array]"); if (currentMixin instanceof Mixin) { mixins.push(currentMixin); } else { mixins.push(new Mixin(undefined, currentMixin)); } } return this; }; /** @method apply @param obj @return applied object */ MixinPrototype.apply = function (obj) { return applyMixin(obj, [this], false); }; MixinPrototype.applyPartial = function (obj) { return applyMixin(obj, [this], true); }; function _detect(curMixin, targetMixin, seen) { var guid = utils.guidFor(curMixin); if (seen[guid]) { return false; } seen[guid] = true; if (curMixin === targetMixin) { return true; } var mixins = curMixin.mixins; var loc = mixins ? mixins.length : 0; while (--loc >= 0) { if (_detect(mixins[loc], targetMixin, seen)) { return true; } } return false; } /** @method detect @param obj @return {Boolean} */ MixinPrototype.detect = function (obj) { if (!obj) { return false; } if (obj instanceof Mixin) { return _detect(obj, this, {}); } var m = obj["__ember_meta__"]; var mixins = m && m.mixins; if (mixins) { return !!mixins[utils.guidFor(this)]; } return false; }; MixinPrototype.without = function () { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } var ret = new Mixin([this]); ret._without = args; return ret; }; function _keys(ret, mixin, seen) { if (seen[utils.guidFor(mixin)]) { return; } seen[utils.guidFor(mixin)] = true; if (mixin.properties) { var props = mixin.properties; for (var key in props) { if (props.hasOwnProperty(key)) { ret[key] = true; } } } else if (mixin.mixins) { array.forEach.call(mixin.mixins, function (x) { _keys(ret, x, seen); }); } } MixinPrototype.keys = function () { var keys = {}; var seen = {}; var ret = []; _keys(keys, this, seen); for (var key in keys) { if (keys.hasOwnProperty(key)) { ret.push(key); } } return ret; }; // returns the mixins currently applied to the specified object // TODO: Make Ember.mixin Mixin.mixins = function (obj) { var m = obj["__ember_meta__"]; var mixins = m && m.mixins; var ret = []; if (!mixins) { return ret; } for (var key in mixins) { var currentMixin = mixins[key]; // skip primitive mixins since these are always anonymous if (!currentMixin.properties) { ret.push(currentMixin); } } return ret; }; REQUIRED = new ember_metal__properties.Descriptor(); REQUIRED.toString = function () { return "(Required Property)"; }; /** Denotes a required property for a mixin @method required @for Ember */ function required() { Ember['default'].deprecate("Ember.required is deprecated as its behavior is inconsistent and unreliable.", false); return REQUIRED; } function Alias(methodName) { this.isDescriptor = true; this.methodName = methodName; } Alias.prototype = new ember_metal__properties.Descriptor(); /** Makes a method available via an additional name. ```javascript App.Person = Ember.Object.extend({ name: function() { return 'Tomhuda Katzdale'; }, moniker: Ember.aliasMethod('name') }); var goodGuy = App.Person.create(); goodGuy.name(); // 'Tomhuda Katzdale' goodGuy.moniker(); // 'Tomhuda Katzdale' ``` @method aliasMethod @for Ember @param {String} methodName name of the method to alias */ function aliasMethod(methodName) { return new Alias(methodName); } // .......................................................... // OBSERVER HELPER // /** Specify a method that observes property changes. ```javascript Ember.Object.extend({ valueObserver: Ember.observer('value', function() { // Executes whenever the "value" property changes }) }); ``` In the future this method may become asynchronous. If you want to ensure synchronous behavior, use `immediateObserver`. Also available as `Function.prototype.observes` if prototype extensions are enabled. @method observer @for Ember @param {String} propertyNames* @param {Function} func @return func */ function observer() { for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } var func = args.slice(-1)[0]; var paths; var addWatchedProperty = function (path) { paths.push(path); }; var _paths = args.slice(0, -1); if (typeof func !== "function") { // revert to old, soft-deprecated argument ordering func = args[0]; _paths = args.slice(1); } paths = []; for (var i = 0; i < _paths.length; ++i) { expandProperties['default'](_paths[i], addWatchedProperty); } if (typeof func !== "function") { throw new Ember['default'].Error("Ember.observer called without a function"); } func.__ember_observes__ = paths; return func; } /** Specify a method that observes property changes. ```javascript Ember.Object.extend({ valueObserver: Ember.immediateObserver('value', function() { // Executes whenever the "value" property changes }) }); ``` In the future, `Ember.observer` may become asynchronous. In this event, `Ember.immediateObserver` will maintain the synchronous behavior. Also available as `Function.prototype.observesImmediately` if prototype extensions are enabled. @method immediateObserver @for Ember @param {String} propertyNames* @param {Function} func @return func */ function immediateObserver() { for (var i = 0, l = arguments.length; i < l; i++) { var arg = arguments[i]; Ember['default'].assert("Immediate observers must observe internal properties only, not properties on other objects.", typeof arg !== "string" || arg.indexOf(".") === -1); } return observer.apply(this, arguments); } /** When observers fire, they are called with the arguments `obj`, `keyName`. Note, `@each.property` observer is called per each add or replace of an element and it's not called with a specific enumeration item. A `beforeObserver` fires before a property changes. A `beforeObserver` is an alternative form of `.observesBefore()`. ```javascript App.PersonView = Ember.View.extend({ friends: [{ name: 'Tom' }, { name: 'Stefan' }, { name: 'Kris' }], valueWillChange: Ember.beforeObserver('content.value', function(obj, keyName) { this.changingFrom = obj.get(keyName); }), valueDidChange: Ember.observer('content.value', function(obj, keyName) { // only run if updating a value already in the DOM if (this.get('state') === 'inDOM') { var color = obj.get(keyName) > this.changingFrom ? 'green' : 'red'; // logic } }), friendsDidChange: Ember.observer('friends.@each.name', function(obj, keyName) { // some logic // obj.get(keyName) returns friends array }) }); ``` Also available as `Function.prototype.observesBefore` if prototype extensions are enabled. @method beforeObserver @for Ember @param {String} propertyNames* @param {Function} func @return func */ function beforeObserver() { for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } var func = args.slice(-1)[0]; var paths; var addWatchedProperty = function (path) { paths.push(path); }; var _paths = args.slice(0, -1); if (typeof func !== "function") { // revert to old, soft-deprecated argument ordering func = args[0]; _paths = args.slice(1); } paths = []; for (var i = 0; i < _paths.length; ++i) { expandProperties['default'](_paths[i], addWatchedProperty); } if (typeof func !== "function") { throw new Ember['default'].Error("Ember.beforeObserver called without a function"); } func.__ember_observesBefore__ = paths; return func; } exports.IS_BINDING = IS_BINDING; exports.REQUIRED = REQUIRED; }); enifed('ember-metal/observer', ['exports', 'ember-metal/watching', 'ember-metal/array', 'ember-metal/events'], function (exports, watching, array, ember_metal__events) { 'use strict'; exports.addObserver = addObserver; exports.observersFor = observersFor; exports.removeObserver = removeObserver; exports.addBeforeObserver = addBeforeObserver; exports._suspendBeforeObserver = _suspendBeforeObserver; exports._suspendObserver = _suspendObserver; exports._suspendBeforeObservers = _suspendBeforeObservers; exports._suspendObservers = _suspendObservers; exports.beforeObserversFor = beforeObserversFor; exports.removeBeforeObserver = removeBeforeObserver; var AFTER_OBSERVERS = ":change"; var BEFORE_OBSERVERS = ":before"; function changeEvent(keyName) { return keyName + AFTER_OBSERVERS; } function beforeEvent(keyName) { return keyName + BEFORE_OBSERVERS; } /** @method addObserver @for Ember @param obj @param {String} path @param {Object|Function} targetOrMethod @param {Function|String} [method] */ function addObserver(obj, _path, target, method) { ember_metal__events.addListener(obj, changeEvent(_path), target, method); watching.watch(obj, _path); return this; } function observersFor(obj, path) { return ember_metal__events.listenersFor(obj, changeEvent(path)); } /** @method removeObserver @for Ember @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] */ function removeObserver(obj, path, target, method) { watching.unwatch(obj, path); ember_metal__events.removeListener(obj, changeEvent(path), target, method); return this; } /** @method addBeforeObserver @for Ember @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] */ function addBeforeObserver(obj, path, target, method) { ember_metal__events.addListener(obj, beforeEvent(path), target, method); watching.watch(obj, path); return this; } // Suspend observer during callback. // // This should only be used by the target of the observer // while it is setting the observed path. function _suspendBeforeObserver(obj, path, target, method, callback) { return ember_metal__events.suspendListener(obj, beforeEvent(path), target, method, callback); } function _suspendObserver(obj, path, target, method, callback) { return ember_metal__events.suspendListener(obj, changeEvent(path), target, method, callback); } function _suspendBeforeObservers(obj, paths, target, method, callback) { var events = array.map.call(paths, beforeEvent); return ember_metal__events.suspendListeners(obj, events, target, method, callback); } function _suspendObservers(obj, paths, target, method, callback) { var events = array.map.call(paths, changeEvent); return ember_metal__events.suspendListeners(obj, events, target, method, callback); } function beforeObserversFor(obj, path) { return ember_metal__events.listenersFor(obj, beforeEvent(path)); } /** @method removeBeforeObserver @for Ember @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] */ function removeBeforeObserver(obj, path, target, method) { watching.unwatch(obj, path); ember_metal__events.removeListener(obj, beforeEvent(path), target, method); return this; } }); enifed('ember-metal/observer_set', ['exports', 'ember-metal/utils', 'ember-metal/events'], function (exports, utils, events) { 'use strict'; exports['default'] = ObserverSet; function ObserverSet() { this.clear(); } ObserverSet.prototype.add = function (sender, keyName, eventName) { var observerSet = this.observerSet; var observers = this.observers; var senderGuid = utils.guidFor(sender); var keySet = observerSet[senderGuid]; var index; if (!keySet) { observerSet[senderGuid] = keySet = {}; } index = keySet[keyName]; if (index === undefined) { index = observers.push({ sender: sender, keyName: keyName, eventName: eventName, listeners: [] }) - 1; keySet[keyName] = index; } return observers[index].listeners; }; ObserverSet.prototype.flush = function () { var observers = this.observers; var i, len, observer, sender; this.clear(); for (i = 0, len = observers.length; i < len; ++i) { observer = observers[i]; sender = observer.sender; if (sender.isDestroying || sender.isDestroyed) { continue; } events.sendEvent(sender, observer.eventName, [sender, observer.keyName], observer.listeners); } }; ObserverSet.prototype.clear = function () { this.observerSet = {}; this.observers = []; }; }); enifed('ember-metal/path_cache', ['exports', 'ember-metal/cache'], function (exports, Cache) { 'use strict'; exports.isGlobal = isGlobal; exports.isGlobalPath = isGlobalPath; exports.hasThis = hasThis; exports.isPath = isPath; exports.getFirstKey = getFirstKey; exports.getTailPath = getTailPath; var IS_GLOBAL = /^[A-Z$]/; var IS_GLOBAL_PATH = /^[A-Z$].*[\.]/; var HAS_THIS = 'this.'; var isGlobalCache = new Cache['default'](1000, function (key) { return IS_GLOBAL.test(key); }); var isGlobalPathCache = new Cache['default'](1000, function (key) { return IS_GLOBAL_PATH.test(key); }); var hasThisCache = new Cache['default'](1000, function (key) { return key.lastIndexOf(HAS_THIS, 0) === 0; }); var firstDotIndexCache = new Cache['default'](1000, function (key) { return key.indexOf('.'); }); var firstKeyCache = new Cache['default'](1000, function (path) { var index = firstDotIndexCache.get(path); if (index === -1) { return path; } else { return path.slice(0, index); } }); var tailPathCache = new Cache['default'](1000, function (path) { var index = firstDotIndexCache.get(path); if (index !== -1) { return path.slice(index + 1); } }); var caches = { isGlobalCache: isGlobalCache, isGlobalPathCache: isGlobalPathCache, hasThisCache: hasThisCache, firstDotIndexCache: firstDotIndexCache, firstKeyCache: firstKeyCache, tailPathCache: tailPathCache };function isGlobal(path) { return isGlobalCache.get(path); } function isGlobalPath(path) { return isGlobalPathCache.get(path); } function hasThis(path) { return hasThisCache.get(path); } function isPath(path) { return firstDotIndexCache.get(path) !== -1; } function getFirstKey(path) { return firstKeyCache.get(path); } function getTailPath(path) { return tailPathCache.get(path); } exports.caches = caches; }); enifed('ember-metal/platform/create', ['exports', 'ember-metal/platform/define_properties'], function (exports, defineProperties) { 'REMOVE_USE_STRICT: true'; /** @class platform @namespace Ember @static */ /** Identical to `Object.create()`. Implements if not available natively. @since 1.8.0 @method create @for Ember */ var create; // ES5 15.2.3.5 // http://es5.github.com/#x15.2.3.5 if (!(Object.create && !Object.create(null).hasOwnProperty)) { /* jshint scripturl:true, proto:true */ // Contributed by Brandon Benvie, October, 2012 var createEmpty; var supportsProto = !({ '__proto__': null } instanceof Object); // the following produces false positives // in Opera Mini => not a reliable check // Object.prototype.__proto__ === null if (supportsProto || typeof document === 'undefined') { createEmpty = function () { return { '__proto__': null }; }; } else { // In old IE __proto__ can't be used to manually set `null`, nor does // any other method exist to make an object that inherits from nothing, // aside from Object.prototype itself. Instead, create a new global // object and *steal* its Object.prototype and strip it bare. This is // used as the prototype to create nullary objects. createEmpty = function () { var iframe = document.createElement('iframe'); var parent = document.body || document.documentElement; iframe.style.display = 'none'; parent.appendChild(iframe); iframe.src = 'javascript:'; var empty = iframe.contentWindow.Object.prototype; parent.removeChild(iframe); iframe = null; delete empty.constructor; delete empty.hasOwnProperty; delete empty.propertyIsEnumerable; delete empty.isPrototypeOf; delete empty.toLocaleString; delete empty.toString; delete empty.valueOf; function Empty() {} Empty.prototype = empty; // short-circuit future calls createEmpty = function () { return new Empty(); }; return new Empty(); }; } create = Object.create = function create(prototype, properties) { var object; function Type() {} // An empty constructor. if (prototype === null) { object = createEmpty(); } else { if (typeof prototype !== 'object' && typeof prototype !== 'function') { // In the native implementation `parent` can be `null` // OR *any* `instanceof Object` (Object|Function|Array|RegExp|etc) // Use `typeof` tho, b/c in old IE, DOM elements are not `instanceof Object` // like they are in modern browsers. Using `Object.create` on DOM elements // is...err...probably inappropriate, but the native version allows for it. throw new TypeError('Object prototype may only be an Object or null'); // same msg as Chrome } Type.prototype = prototype; object = new Type(); } if (properties !== undefined) { defineProperties['default'](object, properties); } return object; }; } else { create = Object.create; } exports['default'] = create; }); enifed('ember-metal/platform/define_properties', ['exports', 'ember-metal/platform/define_property'], function (exports, define_property) { 'use strict'; var defineProperties = Object.defineProperties; // ES5 15.2.3.7 // http://es5.github.com/#x15.2.3.7 if (!defineProperties) { defineProperties = function defineProperties(object, properties) { for (var property in properties) { if (properties.hasOwnProperty(property) && property !== "__proto__") { define_property.defineProperty(object, property, properties[property]); } } return object; }; Object.defineProperties = defineProperties; } exports['default'] = defineProperties; }); enifed('ember-metal/platform/define_property', ['exports'], function (exports) { 'use strict'; /*globals Node */ /** @class platform @namespace Ember @static */ /** Set to true if the platform supports native getters and setters. @property hasPropertyAccessors @final */ /** Identical to `Object.defineProperty()`. Implements as much functionality as possible if not available natively. @method defineProperty @param {Object} obj The object to modify @param {String} keyName property name to modify @param {Object} desc descriptor hash @return {void} */ var defineProperty = (function checkCompliance(defineProperty) { if (!defineProperty) { return; } try { var a = 5; var obj = {}; defineProperty(obj, 'a', { configurable: true, enumerable: true, get: function () { return a; }, set: function (v) { a = v; } }); if (obj.a !== 5) { return; } obj.a = 10; if (a !== 10) { return; } // check non-enumerability defineProperty(obj, 'a', { configurable: true, enumerable: false, writable: true, value: true }); for (var key in obj) { if (key === 'a') { return; } } // Detects a bug in Android <3.2 where you cannot redefine a property using // Object.defineProperty once accessors have already been set. if (obj.a !== true) { return; } // Detects a bug in Android <3 where redefining a property without a value changes the value // Object.defineProperty once accessors have already been set. defineProperty(obj, 'a', { enumerable: false }); if (obj.a !== true) { return; } // defineProperty is compliant return defineProperty; } catch (e) { // IE8 defines Object.defineProperty but calling it on an Object throws return; } })(Object.defineProperty); var hasES5CompliantDefineProperty = !!defineProperty; if (hasES5CompliantDefineProperty && typeof document !== 'undefined') { // This is for Safari 5.0, which supports Object.defineProperty, but not // on DOM nodes. var canDefinePropertyOnDOM = (function () { try { defineProperty(document.createElement('div'), 'definePropertyOnDOM', {}); return true; } catch (e) {} return false; })(); if (!canDefinePropertyOnDOM) { defineProperty = function (obj, keyName, desc) { var isNode; if (typeof Node === 'object') { isNode = obj instanceof Node; } else { isNode = typeof obj === 'object' && typeof obj.nodeType === 'number' && typeof obj.nodeName === 'string'; } if (isNode) { // TODO: Should we have a warning here? return obj[keyName] = desc.value; } else { return Object.defineProperty(obj, keyName, desc); } }; } } if (!hasES5CompliantDefineProperty) { defineProperty = function definePropertyPolyfill(obj, keyName, desc) { if (!desc.get) { obj[keyName] = desc.value; } }; } var hasPropertyAccessors = hasES5CompliantDefineProperty; var canDefineNonEnumerableProperties = hasES5CompliantDefineProperty; exports.hasES5CompliantDefineProperty = hasES5CompliantDefineProperty; exports.defineProperty = defineProperty; exports.hasPropertyAccessors = hasPropertyAccessors; exports.canDefineNonEnumerableProperties = canDefineNonEnumerableProperties; }); enifed('ember-metal/properties', ['exports', 'ember-metal/core', 'ember-metal/utils', 'ember-metal/platform/define_property', 'ember-metal/property_events'], function (exports, Ember, utils, define_property, property_events) { 'use strict'; exports.Descriptor = Descriptor; exports.MANDATORY_SETTER_FUNCTION = MANDATORY_SETTER_FUNCTION; exports.DEFAULT_GETTER_FUNCTION = DEFAULT_GETTER_FUNCTION; exports.defineProperty = defineProperty; function Descriptor() { this.isDescriptor = true; } // .......................................................... // DEFINING PROPERTIES API // function MANDATORY_SETTER_FUNCTION(name) { return function SETTER_FUNCTION(value) { Ember['default'].assert("You must use Ember.set() to set the `" + name + "` property (of " + this + ") to `" + value + "`.", false); }; } function DEFAULT_GETTER_FUNCTION(name) { return function GETTER_FUNCTION() { var meta = this["__ember_meta__"]; return meta && meta.values[name]; }; } /** NOTE: This is a low-level method used by other parts of the API. You almost never want to call this method directly. Instead you should use `Ember.mixin()` to define new properties. Defines a property on an object. This method works much like the ES5 `Object.defineProperty()` method except that it can also accept computed properties and other special descriptors. Normally this method takes only three parameters. However if you pass an instance of `Descriptor` as the third param then you can pass an optional value as the fourth parameter. This is often more efficient than creating new descriptor hashes for each property. ## Examples ```javascript // ES5 compatible mode Ember.defineProperty(contact, 'firstName', { writable: true, configurable: false, enumerable: true, value: 'Charles' }); // define a simple property Ember.defineProperty(contact, 'lastName', undefined, 'Jolley'); // define a computed property Ember.defineProperty(contact, 'fullName', Ember.computed(function() { return this.firstName+' '+this.lastName; }).property('firstName', 'lastName')); ``` @private @method defineProperty @for Ember @param {Object} obj the object to define this property on. This may be a prototype. @param {String} keyName the name of the property @param {Descriptor} [desc] an instance of `Descriptor` (typically a computed property) or an ES5 descriptor. You must provide this or `data` but not both. @param {*} [data] something other than a descriptor, that will become the explicit value of this property. */ function defineProperty(obj, keyName, desc, data, meta) { var possibleDesc, existingDesc, watching, value; if (!meta) { meta = utils.meta(obj); } var watchEntry = meta.watching[keyName]; possibleDesc = obj[keyName]; existingDesc = possibleDesc !== null && typeof possibleDesc === "object" && possibleDesc.isDescriptor ? possibleDesc : undefined; watching = watchEntry !== undefined && watchEntry > 0; if (existingDesc) { existingDesc.teardown(obj, keyName); } if (desc instanceof Descriptor) { value = desc; if (watching && define_property.hasPropertyAccessors) { define_property.defineProperty(obj, keyName, { configurable: true, enumerable: true, writable: true, value: value }); } else { obj[keyName] = value; } if (desc.setup) { desc.setup(obj, keyName); } } else { if (desc == null) { value = data; if (watching && define_property.hasPropertyAccessors) { meta.values[keyName] = data; define_property.defineProperty(obj, keyName, { configurable: true, enumerable: true, set: MANDATORY_SETTER_FUNCTION(keyName), get: DEFAULT_GETTER_FUNCTION(keyName) }); } else { obj[keyName] = data; } } else { value = desc; // compatibility with ES5 define_property.defineProperty(obj, keyName, desc); } } // if key is being watched, override chains that // were initialized with the prototype if (watching) { property_events.overrideChains(obj, keyName, meta); } // The `value` passed to the `didDefineProperty` hook is // either the descriptor or data, whichever was passed. if (obj.didDefineProperty) { obj.didDefineProperty(obj, keyName, value); } return this; } }); enifed('ember-metal/property_events', ['exports', 'ember-metal/utils', 'ember-metal/events', 'ember-metal/observer_set'], function (exports, utils, ember_metal__events, ObserverSet) { 'use strict'; exports.propertyWillChange = propertyWillChange; exports.propertyDidChange = propertyDidChange; exports.overrideChains = overrideChains; exports.beginPropertyChanges = beginPropertyChanges; exports.endPropertyChanges = endPropertyChanges; exports.changeProperties = changeProperties; var PROPERTY_DID_CHANGE = utils.symbol("PROPERTY_DID_CHANGE"); var beforeObserverSet = new ObserverSet['default'](); var observerSet = new ObserverSet['default'](); var deferred = 0; // .......................................................... // PROPERTY CHANGES // /** This function is called just before an object property is about to change. It will notify any before observers and prepare caches among other things. Normally you will not need to call this method directly but if for some reason you can't directly watch a property you can invoke this method manually along with `Ember.propertyDidChange()` which you should call just after the property value changes. @method propertyWillChange @for Ember @param {Object} obj The object with the property that will change @param {String} keyName The property key (or path) that will change. @return {void} */ function propertyWillChange(obj, keyName) { var m = obj["__ember_meta__"]; var watching = m && m.watching[keyName] > 0 || keyName === "length"; var proto = m && m.proto; var possibleDesc = obj[keyName]; var desc = possibleDesc !== null && typeof possibleDesc === "object" && possibleDesc.isDescriptor ? possibleDesc : undefined; if (!watching) { return; } if (proto === obj) { return; } if (desc && desc.willChange) { desc.willChange(obj, keyName); } dependentKeysWillChange(obj, keyName, m); chainsWillChange(obj, keyName, m); notifyBeforeObservers(obj, keyName); } /** This function is called just after an object property has changed. It will notify any observers and clear caches among other things. Normally you will not need to call this method directly but if for some reason you can't directly watch a property you can invoke this method manually along with `Ember.propertyWillChange()` which you should call just before the property value changes. @method propertyDidChange @for Ember @param {Object} obj The object with the property that will change @param {String} keyName The property key (or path) that will change. @return {void} */ function propertyDidChange(obj, keyName) { var m = obj["__ember_meta__"]; var watching = m && m.watching[keyName] > 0 || keyName === "length"; var proto = m && m.proto; var possibleDesc = obj[keyName]; var desc = possibleDesc !== null && typeof possibleDesc === "object" && possibleDesc.isDescriptor ? possibleDesc : undefined; if (proto === obj) { return; } // shouldn't this mean that we're watching this key? if (desc && desc.didChange) { desc.didChange(obj, keyName); } if (obj[PROPERTY_DID_CHANGE]) { obj[PROPERTY_DID_CHANGE](keyName); } if (!watching && keyName !== "length") { return; } if (m && m.deps && m.deps[keyName]) { dependentKeysDidChange(obj, keyName, m); } chainsDidChange(obj, keyName, m, false); notifyObservers(obj, keyName); } var WILL_SEEN, DID_SEEN; // called whenever a property is about to change to clear the cache of any dependent keys (and notify those properties of changes, etc...) function dependentKeysWillChange(obj, depKey, meta) { if (obj.isDestroying) { return; } var deps; if (meta && meta.deps && (deps = meta.deps[depKey])) { var seen = WILL_SEEN; var top = !seen; if (top) { seen = WILL_SEEN = {}; } iterDeps(propertyWillChange, obj, deps, depKey, seen, meta); if (top) { WILL_SEEN = null; } } } // called whenever a property has just changed to update dependent keys function dependentKeysDidChange(obj, depKey, meta) { if (obj.isDestroying) { return; } var deps; if (meta && meta.deps && (deps = meta.deps[depKey])) { var seen = DID_SEEN; var top = !seen; if (top) { seen = DID_SEEN = {}; } iterDeps(propertyDidChange, obj, deps, depKey, seen, meta); if (top) { DID_SEEN = null; } } } function keysOf(obj) { var keys = []; for (var key in obj) { keys.push(key); } return keys; } function iterDeps(method, obj, deps, depKey, seen, meta) { var keys, key, i, possibleDesc, desc; var guid = utils.guidFor(obj); var current = seen[guid]; if (!current) { current = seen[guid] = {}; } if (current[depKey]) { return; } current[depKey] = true; if (deps) { keys = keysOf(deps); for (i = 0; i < keys.length; i++) { key = keys[i]; possibleDesc = obj[key]; desc = possibleDesc !== null && typeof possibleDesc === "object" && possibleDesc.isDescriptor ? possibleDesc : undefined; if (desc && desc._suspended === obj) { continue; } method(obj, key); } } } function chainsWillChange(obj, keyName, m) { if (!(m.hasOwnProperty("chainWatchers") && m.chainWatchers[keyName])) { return; } var nodes = m.chainWatchers[keyName]; var events = []; var i, l; for (i = 0, l = nodes.length; i < l; i++) { nodes[i].willChange(events); } for (i = 0, l = events.length; i < l; i += 2) { propertyWillChange(events[i], events[i + 1]); } } function chainsDidChange(obj, keyName, m, suppressEvents) { if (!(m && m.hasOwnProperty("chainWatchers") && m.chainWatchers[keyName])) { return; } var nodes = m.chainWatchers[keyName]; var events = suppressEvents ? null : []; var i, l; for (i = 0, l = nodes.length; i < l; i++) { nodes[i].didChange(events); } if (suppressEvents) { return; } for (i = 0, l = events.length; i < l; i += 2) { propertyDidChange(events[i], events[i + 1]); } } function overrideChains(obj, keyName, m) { chainsDidChange(obj, keyName, m, true); } /** @method beginPropertyChanges @chainable @private */ function beginPropertyChanges() { deferred++; } /** @method endPropertyChanges @private */ function endPropertyChanges() { deferred--; if (deferred <= 0) { beforeObserverSet.clear(); observerSet.flush(); } } /** Make a series of property changes together in an exception-safe way. ```javascript Ember.changeProperties(function() { obj1.set('foo', mayBlowUpWhenSet); obj2.set('bar', baz); }); ``` @method changeProperties @param {Function} callback @param [binding] */ function changeProperties(callback, binding) { beginPropertyChanges(); utils.tryFinally(callback, endPropertyChanges, binding); } function notifyBeforeObservers(obj, keyName) { if (obj.isDestroying) { return; } var eventName = keyName + ":before"; var listeners, added; if (deferred) { listeners = beforeObserverSet.add(obj, keyName, eventName); added = ember_metal__events.accumulateListeners(obj, eventName, listeners); ember_metal__events.sendEvent(obj, eventName, [obj, keyName], added); } else { ember_metal__events.sendEvent(obj, eventName, [obj, keyName]); } } function notifyObservers(obj, keyName) { if (obj.isDestroying) { return; } var eventName = keyName + ":change"; var listeners; if (deferred) { listeners = observerSet.add(obj, keyName, eventName); ember_metal__events.accumulateListeners(obj, eventName, listeners); } else { ember_metal__events.sendEvent(obj, eventName, [obj, keyName]); } } exports.PROPERTY_DID_CHANGE = PROPERTY_DID_CHANGE; }); enifed('ember-metal/property_get', ['exports', 'ember-metal/core', 'ember-metal/error', 'ember-metal/path_cache', 'ember-metal/platform/define_property', 'ember-metal/utils', 'ember-metal/is_none'], function (exports, Ember, EmberError, path_cache, define_property, utils, isNone) { 'use strict'; exports.get = get; exports.normalizeTuple = normalizeTuple; exports._getPath = _getPath; exports.getWithDefault = getWithDefault; var FIRST_KEY = /^([^\.]+)/; var INTERCEPT_GET = utils.symbol("INTERCEPT_GET"); var UNHANDLED_GET = utils.symbol("UNHANDLED_GET"); function get(obj, keyName) { // Helpers that operate with 'this' within an #each if (keyName === "") { return obj; } if (!keyName && "string" === typeof obj) { keyName = obj; obj = Ember['default'].lookup; } Ember['default'].assert("Cannot call get with " + keyName + " key.", !!keyName); Ember['default'].assert("Cannot call get with '" + keyName + "' on an undefined object.", obj !== undefined); if (isNone['default'](obj)) { return _getPath(obj, keyName); } if (obj && typeof obj[INTERCEPT_GET] === "function") { var result = obj[INTERCEPT_GET](obj, keyName); if (result !== UNHANDLED_GET) { return result; } } var meta = obj["__ember_meta__"]; var possibleDesc = obj[keyName]; var desc = possibleDesc !== null && typeof possibleDesc === "object" && possibleDesc.isDescriptor ? possibleDesc : undefined; var ret; if (desc === undefined && path_cache.isPath(keyName)) { return _getPath(obj, keyName); } if (desc) { return desc.get(obj, keyName); } else { if (define_property.hasPropertyAccessors && meta && meta.watching[keyName] > 0) { ret = meta.values[keyName]; } else { ret = obj[keyName]; } if (ret === undefined && "object" === typeof obj && !(keyName in obj) && "function" === typeof obj.unknownProperty) { return obj.unknownProperty(keyName); } return ret; } } /** Normalizes a target/path pair to reflect that actual target/path that should be observed, etc. This takes into account passing in global property paths (i.e. a path beginning with a capital letter not defined on the target). @private @method normalizeTuple @for Ember @param {Object} target The current target. May be `null`. @param {String} path A path on the target or a global property path. @return {Array} a temporary array with the normalized target/path pair. */ function normalizeTuple(target, path) { var hasThis = path_cache.hasThis(path); var isGlobal = !hasThis && path_cache.isGlobal(path); var key; if (!target && !isGlobal) { return [undefined, ""]; } if (hasThis) { path = path.slice(5); } if (!target || isGlobal) { target = Ember['default'].lookup; } if (isGlobal && path_cache.isPath(path)) { key = path.match(FIRST_KEY)[0]; target = get(target, key); path = path.slice(key.length + 1); } // must return some kind of path to be valid else other things will break. validateIsPath(path); return [target, path]; } function validateIsPath(path) { if (!path || path.length === 0) { throw new EmberError['default']("Object in path " + path + " could not be found or was destroyed."); } } function _getPath(root, path) { var hasThis, parts, tuple, idx, len; // detect complicated paths and normalize them hasThis = path_cache.hasThis(path); if (!root || hasThis) { tuple = normalizeTuple(root, path); root = tuple[0]; path = tuple[1]; tuple.length = 0; } parts = path.split("."); len = parts.length; for (idx = 0; root != null && idx < len; idx++) { root = get(root, parts[idx], true); if (root && root.isDestroyed) { return undefined; } } return root; } function getWithDefault(root, key, defaultValue) { var value = get(root, key); if (value === undefined) { return defaultValue; } return value; } exports['default'] = get; exports.INTERCEPT_GET = INTERCEPT_GET; exports.UNHANDLED_GET = UNHANDLED_GET; }); enifed('ember-metal/property_set', ['exports', 'ember-metal/core', 'ember-metal/property_get', 'ember-metal/property_events', 'ember-metal/properties', 'ember-metal/error', 'ember-metal/path_cache', 'ember-metal/platform/define_property', 'ember-metal/utils'], function (exports, Ember, property_get, property_events, properties, EmberError, path_cache, define_property, utils) { 'use strict'; exports.set = set; exports.trySet = trySet; var INTERCEPT_SET = utils.symbol("INTERCEPT_SET"); var UNHANDLED_SET = utils.symbol("UNHANDLED_SET"); function set(obj, keyName, value, tolerant) { if (typeof obj === "string") { Ember['default'].assert("Path '" + obj + "' must be global if no obj is given.", path_cache.isGlobalPath(obj)); value = keyName; keyName = obj; obj = Ember['default'].lookup; } Ember['default'].assert("Cannot call set with '" + keyName + "' key.", !!keyName); if (obj === Ember['default'].lookup) { return setPath(obj, keyName, value, tolerant); } // This path exists purely to implement backwards-compatible // effects (specifically, setting a property on a view may // invoke a mutator on `attrs`). if (obj && typeof obj[INTERCEPT_SET] === "function") { var result = obj[INTERCEPT_SET](obj, keyName, value, tolerant); if (result !== UNHANDLED_SET) { return result; } } var meta, possibleDesc, desc; if (obj) { meta = obj["__ember_meta__"]; possibleDesc = obj[keyName]; desc = possibleDesc !== null && typeof possibleDesc === "object" && possibleDesc.isDescriptor ? possibleDesc : undefined; } var isUnknown, currentValue; if ((!obj || desc === undefined) && path_cache.isPath(keyName)) { return setPath(obj, keyName, value, tolerant); } Ember['default'].assert("You need to provide an object and key to `set`.", !!obj && keyName !== undefined); Ember['default'].assert("calling set on destroyed object", !obj.isDestroyed); if (desc) { desc.set(obj, keyName, value); } else { if (obj !== null && value !== undefined && typeof obj === "object" && obj[keyName] === value) { return value; } isUnknown = "object" === typeof obj && !(keyName in obj); // setUnknownProperty is called if `obj` is an object, // the property does not already exist, and the // `setUnknownProperty` method exists on the object if (isUnknown && "function" === typeof obj.setUnknownProperty) { obj.setUnknownProperty(keyName, value); } else if (meta && meta.watching[keyName] > 0) { if (meta.proto !== obj) { if (define_property.hasPropertyAccessors) { currentValue = meta.values[keyName]; } else { currentValue = obj[keyName]; } } // only trigger a change if the value has changed if (value !== currentValue) { property_events.propertyWillChange(obj, keyName); if (define_property.hasPropertyAccessors) { if (currentValue === undefined && !(keyName in obj) || !Object.prototype.propertyIsEnumerable.call(obj, keyName)) { properties.defineProperty(obj, keyName, null, value); // setup mandatory setter } else { meta.values[keyName] = value; } } else { obj[keyName] = value; } property_events.propertyDidChange(obj, keyName); } } else { obj[keyName] = value; if (obj[property_events.PROPERTY_DID_CHANGE]) { obj[property_events.PROPERTY_DID_CHANGE](keyName); } } } return value; } function setPath(root, path, value, tolerant) { var keyName; // get the last part of the path keyName = path.slice(path.lastIndexOf(".") + 1); // get the first part of the part path = path === keyName ? keyName : path.slice(0, path.length - (keyName.length + 1)); // unless the path is this, look up the first part to // get the root if (path !== "this") { root = property_get._getPath(root, path); } if (!keyName || keyName.length === 0) { throw new EmberError['default']("Property set failed: You passed an empty path"); } if (!root) { if (tolerant) { return; } else { throw new EmberError['default']("Property set failed: object in path \"" + path + "\" could not be found or was destroyed."); } } return set(root, keyName, value); } /** Error-tolerant form of `Ember.set`. Will not blow up if any part of the chain is `undefined`, `null`, or destroyed. This is primarily used when syncing bindings, which may try to update after an object has been destroyed. @method trySet @for Ember @param {Object} obj The object to modify. @param {String} path The property path to set @param {Object} value The value to set */ function trySet(root, path, value) { return set(root, path, value, true); } exports.INTERCEPT_SET = INTERCEPT_SET; exports.UNHANDLED_SET = UNHANDLED_SET; }); enifed('ember-metal/run_loop', ['exports', 'ember-metal/core', 'ember-metal/utils', 'ember-metal/array', 'ember-metal/property_events', 'backburner'], function (exports, Ember, utils, array, property_events, Backburner) { 'use strict'; function onBegin(current) { run.currentRunLoop = current; } function onEnd(current, next) { run.currentRunLoop = next; } // ES6TODO: should Backburner become es6? var backburner = new Backburner['default'](['sync', 'actions', 'destroy'], { GUID_KEY: utils.GUID_KEY, sync: { before: property_events.beginPropertyChanges, after: property_events.endPropertyChanges }, defaultQueue: 'actions', onBegin: onBegin, onEnd: onEnd, onErrorTarget: Ember['default'], onErrorMethod: 'onerror' }); // .......................................................... // run - this is ideally the only public API the dev sees // /** Runs the passed target and method inside of a RunLoop, ensuring any deferred actions including bindings and views updates are flushed at the end. Normally you should not need to invoke this method yourself. However if you are implementing raw event handlers when interfacing with other libraries or plugins, you should probably wrap all of your code inside this call. ```javascript run(function() { // code to be executed within a RunLoop }); ``` @class run @namespace Ember @static @constructor @param {Object} [target] target of method to call @param {Function|String} method Method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Any additional arguments you wish to pass to the method. @return {Object} return value from invoking the passed function. */ exports['default'] = run; function run() { return backburner.run.apply(backburner, arguments); } /** If no run-loop is present, it creates a new one. If a run loop is present it will queue itself to run on the existing run-loops action queue. Please note: This is not for normal usage, and should be used sparingly. If invoked when not within a run loop: ```javascript run.join(function() { // creates a new run-loop }); ``` Alternatively, if called within an existing run loop: ```javascript run(function() { // creates a new run-loop run.join(function() { // joins with the existing run-loop, and queues for invocation on // the existing run-loops action queue. }); }); ``` @method join @namespace Ember @param {Object} [target] target of method to call @param {Function|String} method Method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Any additional arguments you wish to pass to the method. @return {Object} Return value from invoking the passed function. Please note, when called within an existing loop, no return value is possible. */ run.join = function () { return backburner.join.apply(backburner, arguments); }; /** Allows you to specify which context to call the specified function in while adding the execution of that function to the Ember run loop. This ability makes this method a great way to asynchronously integrate third-party libraries into your Ember application. `run.bind` takes two main arguments, the desired context and the function to invoke in that context. Any additional arguments will be supplied as arguments to the function that is passed in. Let's use the creation of a TinyMCE component as an example. Currently, TinyMCE provides a setup configuration option we can use to do some processing after the TinyMCE instance is initialized but before it is actually rendered. We can use that setup option to do some additional setup for our component. The component itself could look something like the following: ```javascript App.RichTextEditorComponent = Ember.Component.extend({ initializeTinyMCE: Ember.on('didInsertElement', function() { tinymce.init({ selector: '#' + this.$().prop('id'), setup: Ember.run.bind(this, this.setupEditor) }); }), setupEditor: function(editor) { this.set('editor', editor); editor.on('change', function() { console.log('content changed!'); }); } }); ``` In this example, we use Ember.run.bind to bind the setupEditor method to the context of the App.RichTextEditorComponent and to have the invocation of that method be safely handled and executed by the Ember run loop. @method bind @namespace Ember @param {Object} [target] target of method to call @param {Function|String} method Method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Any additional arguments you wish to pass to the method. @return {Function} returns a new function that will always have a particular context @since 1.4.0 */ run.bind = function () { for (var _len = arguments.length, curried = Array(_len), _key = 0; _key < _len; _key++) { curried[_key] = arguments[_key]; } return function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return run.join.apply(run, curried.concat(args)); }; }; run.backburner = backburner; run.currentRunLoop = null; run.queues = backburner.queueNames; /** Begins a new RunLoop. Any deferred actions invoked after the begin will be buffered until you invoke a matching call to `run.end()`. This is a lower-level way to use a RunLoop instead of using `run()`. ```javascript run.begin(); // code to be executed within a RunLoop run.end(); ``` @method begin @return {void} */ run.begin = function () { backburner.begin(); }; /** Ends a RunLoop. This must be called sometime after you call `run.begin()` to flush any deferred actions. This is a lower-level way to use a RunLoop instead of using `run()`. ```javascript run.begin(); // code to be executed within a RunLoop run.end(); ``` @method end @return {void} */ run.end = function () { backburner.end(); }; /** Array of named queues. This array determines the order in which queues are flushed at the end of the RunLoop. You can define your own queues by simply adding the queue name to this array. Normally you should not need to inspect or modify this property. @property queues @type Array @default ['sync', 'actions', 'destroy'] */ /** Adds the passed target/method and any optional arguments to the named queue to be executed at the end of the RunLoop. If you have not already started a RunLoop when calling this method one will be started for you automatically. At the end of a RunLoop, any methods scheduled in this way will be invoked. Methods will be invoked in an order matching the named queues defined in the `run.queues` property. ```javascript run.schedule('sync', this, function() { // this will be executed in the first RunLoop queue, when bindings are synced console.log('scheduled on sync queue'); }); run.schedule('actions', this, function() { // this will be executed in the 'actions' queue, after bindings have synced. console.log('scheduled on actions queue'); }); // Note the functions will be run in order based on the run queues order. // Output would be: // scheduled on sync queue // scheduled on actions queue ``` @method schedule @param {String} queue The name of the queue to schedule against. Default queues are 'sync' and 'actions' @param {Object} [target] target object to use as the context when invoking a method. @param {String|Function} method The method to invoke. If you pass a string it will be resolved on the target object at the time the scheduled item is invoked allowing you to change the target function. @param {Object} [arguments*] Optional arguments to be passed to the queued method. @return {void} */ run.schedule = function () { checkAutoRun(); backburner.schedule.apply(backburner, arguments); }; // Used by global test teardown run.hasScheduledTimers = function () { return backburner.hasTimers(); }; // Used by global test teardown run.cancelTimers = function () { backburner.cancelTimers(); }; /** Immediately flushes any events scheduled in the 'sync' queue. Bindings use this queue so this method is a useful way to immediately force all bindings in the application to sync. You should call this method anytime you need any changed state to propagate throughout the app immediately without repainting the UI (which happens in the later 'render' queue added by the `ember-views` package). ```javascript run.sync(); ``` @method sync @return {void} */ run.sync = function () { if (backburner.currentInstance) { backburner.currentInstance.queues.sync.flush(); } }; /** Invokes the passed target/method and optional arguments after a specified period of time. The last parameter of this method must always be a number of milliseconds. You should use this method whenever you need to run some action after a period of time instead of using `setTimeout()`. This method will ensure that items that expire during the same script execution cycle all execute together, which is often more efficient than using a real setTimeout. ```javascript run.later(myContext, function() { // code here will execute within a RunLoop in about 500ms with this == myContext }, 500); ``` @method later @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @param {Number} wait Number of milliseconds to wait. @return {*} Timer information for use in cancelling, see `run.cancel`. */ run.later = function () { return backburner.later.apply(backburner, arguments); }; /** Schedule a function to run one time during the current RunLoop. This is equivalent to calling `scheduleOnce` with the "actions" queue. @method once @param {Object} [target] The target of the method to invoke. @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} Timer information for use in cancelling, see `run.cancel`. */ run.once = function () { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } checkAutoRun(); args.unshift('actions'); return backburner.scheduleOnce.apply(backburner, args); }; /** Schedules a function to run one time in a given queue of the current RunLoop. Calling this method with the same queue/target/method combination will have no effect (past the initial call). Note that although you can pass optional arguments these will not be considered when looking for duplicates. New arguments will replace previous calls. ```javascript function sayHi() { console.log('hi'); } run(function() { run.scheduleOnce('afterRender', myContext, sayHi); run.scheduleOnce('afterRender', myContext, sayHi); // sayHi will only be executed once, in the afterRender queue of the RunLoop }); ``` Also note that passing an anonymous function to `run.scheduleOnce` will not prevent additional calls with an identical anonymous function from scheduling the items multiple times, e.g.: ```javascript function scheduleIt() { run.scheduleOnce('actions', myContext, function() { console.log('Closure'); }); } scheduleIt(); scheduleIt(); // "Closure" will print twice, even though we're using `run.scheduleOnce`, // because the function we pass to it is anonymous and won't match the // previously scheduled operation. ``` Available queues, and their order, can be found at `run.queues` @method scheduleOnce @param {String} [queue] The name of the queue to schedule against. Default queues are 'sync' and 'actions'. @param {Object} [target] The target of the method to invoke. @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} Timer information for use in cancelling, see `run.cancel`. */ run.scheduleOnce = function () { checkAutoRun(); return backburner.scheduleOnce.apply(backburner, arguments); }; /** Schedules an item to run from within a separate run loop, after control has been returned to the system. This is equivalent to calling `run.later` with a wait time of 1ms. ```javascript run.next(myContext, function() { // code to be executed in the next run loop, // which will be scheduled after the current one }); ``` Multiple operations scheduled with `run.next` will coalesce into the same later run loop, along with any other operations scheduled by `run.later` that expire right around the same time that `run.next` operations will fire. Note that there are often alternatives to using `run.next`. For instance, if you'd like to schedule an operation to happen after all DOM element operations have completed within the current run loop, you can make use of the `afterRender` run loop queue (added by the `ember-views` package, along with the preceding `render` queue where all the DOM element operations happen). Example: ```javascript App.MyCollectionView = Ember.CollectionView.extend({ didInsertElement: function() { run.scheduleOnce('afterRender', this, 'processChildElements'); }, processChildElements: function() { // ... do something with collectionView's child view // elements after they've finished rendering, which // can't be done within the CollectionView's // `didInsertElement` hook because that gets run // before the child elements have been added to the DOM. } }); ``` One benefit of the above approach compared to using `run.next` is that you will be able to perform DOM/CSS operations before unprocessed elements are rendered to the screen, which may prevent flickering or other artifacts caused by delaying processing until after rendering. The other major benefit to the above approach is that `run.next` introduces an element of non-determinism, which can make things much harder to test, due to its reliance on `setTimeout`; it's much harder to guarantee the order of scheduled operations when they are scheduled outside of the current run loop, i.e. with `run.next`. @method next @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} Timer information for use in cancelling, see `run.cancel`. */ run.next = function () { for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } args.push(1); return backburner.later.apply(backburner, args); }; /** Cancels a scheduled item. Must be a value returned by `run.later()`, `run.once()`, `run.next()`, `run.debounce()`, or `run.throttle()`. ```javascript var runNext = run.next(myContext, function() { // will not be executed }); run.cancel(runNext); var runLater = run.later(myContext, function() { // will not be executed }, 500); run.cancel(runLater); var runOnce = run.once(myContext, function() { // will not be executed }); run.cancel(runOnce); var throttle = run.throttle(myContext, function() { // will not be executed }, 1, false); run.cancel(throttle); var debounce = run.debounce(myContext, function() { // will not be executed }, 1); run.cancel(debounce); var debounceImmediate = run.debounce(myContext, function() { // will be executed since we passed in true (immediate) }, 100, true); // the 100ms delay until this method can be called again will be cancelled run.cancel(debounceImmediate); ``` @method cancel @param {Object} timer Timer object to cancel @return {Boolean} true if cancelled or false/undefined if it wasn't found */ run.cancel = function (timer) { return backburner.cancel(timer); }; /** Delay calling the target method until the debounce period has elapsed with no additional debounce calls. If `debounce` is called again before the specified time has elapsed, the timer is reset and the entire period must pass again before the target method is called. This method should be used when an event may be called multiple times but the action should only be called once when the event is done firing. A common example is for scroll events where you only want updates to happen once scrolling has ceased. ```javascript function whoRan() { console.log(this.name + ' ran.'); } var myContext = { name: 'debounce' }; run.debounce(myContext, whoRan, 150); // less than 150ms passes run.debounce(myContext, whoRan, 150); // 150ms passes // whoRan is invoked with context myContext // console logs 'debounce ran.' one time. ``` Immediate allows you to run the function immediately, but debounce other calls for this function until the wait time has elapsed. If `debounce` is called again before the specified time has elapsed, the timer is reset and the entire period must pass again before the method can be called again. ```javascript function whoRan() { console.log(this.name + ' ran.'); } var myContext = { name: 'debounce' }; run.debounce(myContext, whoRan, 150, true); // console logs 'debounce ran.' one time immediately. // 100ms passes run.debounce(myContext, whoRan, 150, true); // 150ms passes and nothing else is logged to the console and // the debouncee is no longer being watched run.debounce(myContext, whoRan, 150, true); // console logs 'debounce ran.' one time immediately. // 150ms passes and nothing else is logged to the console and // the debouncee is no longer being watched ``` @method debounce @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Optional arguments to pass to the timeout. @param {Number} wait Number of milliseconds to wait. @param {Boolean} immediate Trigger the function on the leading instead of the trailing edge of the wait interval. Defaults to false. @return {Array} Timer information for use in cancelling, see `run.cancel`. */ run.debounce = function () { return backburner.debounce.apply(backburner, arguments); }; /** Ensure that the target method is never called more frequently than the specified spacing period. The target method is called immediately. ```javascript function whoRan() { console.log(this.name + ' ran.'); } var myContext = { name: 'throttle' }; run.throttle(myContext, whoRan, 150); // whoRan is invoked with context myContext // console logs 'throttle ran.' // 50ms passes run.throttle(myContext, whoRan, 150); // 50ms passes run.throttle(myContext, whoRan, 150); // 150ms passes run.throttle(myContext, whoRan, 150); // whoRan is invoked with context myContext // console logs 'throttle ran.' ``` @method throttle @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Optional arguments to pass to the timeout. @param {Number} spacing Number of milliseconds to space out requests. @param {Boolean} immediate Trigger the function on the leading instead of the trailing edge of the wait interval. Defaults to true. @return {Array} Timer information for use in cancelling, see `run.cancel`. */ run.throttle = function () { return backburner.throttle.apply(backburner, arguments); }; // Make sure it's not an autorun during testing function checkAutoRun() { if (!run.currentRunLoop) { Ember['default'].assert('You have turned on testing mode, which disabled the run-loop\'s autorun.\n You will need to wrap any code with asynchronous side-effects in a run', !Ember['default'].testing); } } /** Add a new named queue after the specified queue. The queue to add will only be added once. @method _addQueue @param {String} name the name of the queue to add. @param {String} after the name of the queue to add after. @private */ run._addQueue = function (name, after) { if (array.indexOf.call(run.queues, name) === -1) { run.queues.splice(array.indexOf.call(run.queues, after) + 1, 0, name); } }; /* queue, target, method */ /*target, method*/ /*queue, target, method*/ }); enifed('ember-metal/set_properties', ['exports', 'ember-metal/property_events', 'ember-metal/property_set', 'ember-metal/keys'], function (exports, property_events, property_set, keys) { 'use strict'; exports['default'] = setProperties; function setProperties(obj, properties) { if (!properties || typeof properties !== "object") { return obj; } property_events.changeProperties(function () { var props = keys['default'](properties); var propertyName; for (var i = 0, l = props.length; i < l; i++) { propertyName = props[i]; property_set.set(obj, propertyName, properties[propertyName]); } }); return obj; } }); enifed('ember-metal/streams/conditional', ['exports', 'ember-metal/streams/stream', 'ember-metal/streams/utils', 'ember-metal/platform/create'], function (exports, Stream, utils, create) { 'use strict'; exports['default'] = conditional; function conditional(test, consequent, alternate) { if (utils.isStream(test)) { return new ConditionalStream(test, consequent, alternate); } else { if (test) { return consequent; } else { return alternate; } } } function ConditionalStream(test, consequent, alternate) { this.init(); this.oldTestResult = undefined; this.test = test; this.consequent = consequent; this.alternate = alternate; } ConditionalStream.prototype = create['default'](Stream['default'].prototype); ConditionalStream.prototype.compute = function () { var oldTestResult = this.oldTestResult; var newTestResult = !!utils.read(this.test); if (newTestResult !== oldTestResult) { switch (oldTestResult) { case true: utils.unsubscribe(this.consequent, this.notify, this);break; case false: utils.unsubscribe(this.alternate, this.notify, this);break; case undefined: utils.subscribe(this.test, this.notify, this); } switch (newTestResult) { case true: utils.subscribe(this.consequent, this.notify, this);break; case false: utils.subscribe(this.alternate, this.notify, this); } this.oldTestResult = newTestResult; } return newTestResult ? utils.read(this.consequent) : utils.read(this.alternate); }; }); enifed('ember-metal/streams/dependency', ['exports', 'ember-metal/core', 'ember-metal/merge', 'ember-metal/streams/utils'], function (exports, Ember, merge, utils) { 'use strict'; function Dependency(depender, dependee) { Ember['default'].assert("Dependency error: Depender must be a stream", utils.isStream(depender)); this.next = null; this.prev = null; this.depender = depender; this.dependee = dependee; this.unsubscription = null; } merge['default'](Dependency.prototype, { subscribe: function () { Ember['default'].assert("Dependency error: Dependency tried to subscribe while already subscribed", !this.unsubscription); this.unsubscription = utils.subscribe(this.dependee, this.depender.notify, this.depender); }, unsubscribe: function () { if (this.unsubscription) { this.unsubscription(); this.unsubscription = null; } }, replace: function (dependee) { if (this.dependee !== dependee) { this.dependee = dependee; if (this.unsubscription) { this.unsubscribe(); this.subscribe(); } } }, getValue: function () { return utils.read(this.dependee); }, setValue: function (value) { return utils.setValue(this.dependee, value); } // destroy() { // var next = this.next; // var prev = this.prev; // if (prev) { // prev.next = next; // } else { // this.depender.dependencyHead = next; // } // if (next) { // next.prev = prev; // } else { // this.depender.dependencyTail = prev; // } // this.unsubscribe(); // } }); exports['default'] = Dependency; }); enifed('ember-metal/streams/key-stream', ['exports', 'ember-metal/core', 'ember-metal/merge', 'ember-metal/platform/create', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/observer', 'ember-metal/streams/stream', 'ember-metal/streams/utils'], function (exports, Ember, merge, create, property_get, property_set, observer, Stream, utils) { 'use strict'; function KeyStream(source, key) { Ember['default'].assert('KeyStream error: source must be a stream', utils.isStream(source)); // TODO: This isn't necessary. Ember['default'].assert('KeyStream error: key must be a non-empty string', typeof key === 'string' && key.length > 0); Ember['default'].assert('KeyStream error: key must not have a \'.\'', key.indexOf('.') === -1); // used to get the original path for debugging and legacy purposes var label = labelFor(source, key); this.init(label); this.path = label; this.sourceDep = this.addMutableDependency(source); this.observedObject = null; this.key = key; } function labelFor(source, key) { return source.label ? source.label + '.' + key : key; } KeyStream.prototype = create['default'](Stream['default'].prototype); merge['default'](KeyStream.prototype, { compute: function () { var object = this.sourceDep.getValue(); if (object) { return property_get.get(object, this.key); } }, setValue: function (value) { var object = this.sourceDep.getValue(); if (object) { property_set.set(object, this.key, value); } }, setSource: function (source) { this.sourceDep.replace(source); this.notify(); }, _super$revalidate: Stream['default'].prototype.revalidate, revalidate: function (value) { this._super$revalidate(value); var object = this.sourceDep.getValue(); if (object !== this.observedObject) { this.deactivate(); if (object && typeof object === 'object') { observer.addObserver(object, this.key, this, this.notify); this.observedObject = object; } } }, _super$deactivate: Stream['default'].prototype.deactivate, deactivate: function () { this._super$deactivate(); if (this.observedObject) { observer.removeObserver(this.observedObject, this.key, this, this.notify); this.observedObject = null; } } }); exports['default'] = KeyStream; }); enifed('ember-metal/streams/proxy-stream', ['exports', 'ember-metal/merge', 'ember-metal/streams/stream', 'ember-metal/platform/create'], function (exports, merge, Stream, create) { 'use strict'; function ProxyStream(source, label) { this.init(label); this.sourceDep = this.addMutableDependency(source); } ProxyStream.prototype = create['default'](Stream['default'].prototype); merge['default'](ProxyStream.prototype, { compute: function () { return this.sourceDep.getValue(); }, setValue: function (value) { this.sourceDep.setValue(value); }, setSource: function (source) { this.sourceDep.replace(source); this.notify(); } }); exports['default'] = ProxyStream; }); enifed('ember-metal/streams/stream', ['exports', 'ember-metal/core', 'ember-metal/platform/create', 'ember-metal/path_cache', 'ember-metal/observer', 'ember-metal/streams/utils', 'ember-metal/streams/subscriber', 'ember-metal/streams/dependency'], function (exports, Ember, create, path_cache, observer, utils, Subscriber, Dependency) { 'use strict'; function Stream(fn, label) { this.init(label); this.compute = fn; } var KeyStream; var ProxyMixin; Stream.prototype = { isStream: true, init: function (label) { this.label = makeLabel(label); this.isActive = false; this.isDirty = true; this.isDestroyed = false; this.cache = undefined; this.children = undefined; this.subscriberHead = null; this.subscriberTail = null; this.dependencyHead = null; this.dependencyTail = null; this.observedProxy = null; }, _makeChildStream: function (key) { KeyStream = KeyStream || Ember['default'].__loader.require("ember-metal/streams/key-stream")["default"]; return new KeyStream(this, key); }, removeChild: function (key) { delete this.children[key]; }, getKey: function (key) { if (this.children === undefined) { this.children = create['default'](null); } var keyStream = this.children[key]; if (keyStream === undefined) { keyStream = this._makeChildStream(key); this.children[key] = keyStream; } return keyStream; }, get: function (path) { var firstKey = path_cache.getFirstKey(path); var tailPath = path_cache.getTailPath(path); if (this.children === undefined) { this.children = create['default'](null); } var keyStream = this.children[firstKey]; if (keyStream === undefined) { keyStream = this._makeChildStream(firstKey, path); this.children[firstKey] = keyStream; } if (tailPath === undefined) { return keyStream; } else { return keyStream.get(tailPath); } }, value: function () { // TODO: Ensure value is never called on a destroyed stream // so that we can uncomment this assertion. // // Ember.assert("Stream error: value was called after the stream was destroyed", !this.isDestroyed); // TODO: Remove this block. This will require ensuring we are // not treating streams as "volatile" anywhere. if (!this.isActive) { this.isDirty = true; } var willRevalidate = false; if (!this.isActive && this.subscriberHead) { this.activate(); willRevalidate = true; } if (this.isDirty) { if (this.isActive) { willRevalidate = true; } this.cache = this.compute(); this.isDirty = false; } if (willRevalidate) { this.revalidate(this.cache); } return this.cache; }, addMutableDependency: function (object) { var dependency = new Dependency['default'](this, object); if (this.isActive) { dependency.subscribe(); } if (this.dependencyHead === null) { this.dependencyHead = this.dependencyTail = dependency; } else { var tail = this.dependencyTail; tail.next = dependency; dependency.prev = tail; this.dependencyTail = dependency; } return dependency; }, addDependency: function (object) { if (utils.isStream(object)) { this.addMutableDependency(object); } }, subscribeDependencies: function () { var dependency = this.dependencyHead; while (dependency) { var next = dependency.next; dependency.subscribe(); dependency = next; } }, unsubscribeDependencies: function () { var dependency = this.dependencyHead; while (dependency) { var next = dependency.next; dependency.unsubscribe(); dependency = next; } }, maybeDeactivate: function () { if (!this.subscriberHead && this.isActive) { this.isActive = false; this.unsubscribeDependencies(); this.deactivate(); } }, activate: function () { this.isActive = true; this.subscribeDependencies(); }, revalidate: function (value) { if (value !== this.observedProxy) { this.deactivate(); ProxyMixin = ProxyMixin || Ember['default'].__loader.require("ember-runtime/mixins/-proxy")["default"]; if (ProxyMixin.detect(value)) { observer.addObserver(value, "content", this, this.notify); this.observedProxy = value; } } }, deactivate: function () { if (this.observedProxy) { observer.removeObserver(this.observedProxy, "content", this, this.notify); this.observedProxy = null; } }, compute: function () { throw new Error("Stream error: compute not implemented"); }, setValue: function () { throw new Error("Stream error: setValue not implemented"); }, notify: function () { this.notifyExcept(); }, notifyExcept: function (callbackToSkip, contextToSkip) { if (!this.isDirty) { this.isDirty = true; this.notifySubscribers(callbackToSkip, contextToSkip); } }, subscribe: function (callback, context) { Ember['default'].assert("You tried to subscribe to a stream but the callback provided was not a function.", typeof callback === "function"); var subscriber = new Subscriber['default'](callback, context, this); if (this.subscriberHead === null) { this.subscriberHead = this.subscriberTail = subscriber; } else { var tail = this.subscriberTail; tail.next = subscriber; subscriber.prev = tail; this.subscriberTail = subscriber; } var stream = this; return function (prune) { subscriber.removeFrom(stream); if (prune) { stream.prune(); } }; }, prune: function () { if (this.subscriberHead === null) { this.destroy(true); } }, unsubscribe: function (callback, context) { var subscriber = this.subscriberHead; while (subscriber) { var next = subscriber.next; if (subscriber.callback === callback && subscriber.context === context) { subscriber.removeFrom(this); } subscriber = next; } }, notifySubscribers: function (callbackToSkip, contextToSkip) { var subscriber = this.subscriberHead; while (subscriber) { var next = subscriber.next; var callback = subscriber.callback; var context = subscriber.context; subscriber = next; if (callback === callbackToSkip && context === contextToSkip) { continue; } if (context === undefined) { callback(this); } else { callback.call(context, this); } } }, destroy: function (prune) { if (!this.isDestroyed) { this.isDestroyed = true; this.subscriberHead = this.subscriberTail = null; this.maybeDeactivate(); var dependencies = this.dependencies; if (dependencies) { for (var i = 0, l = dependencies.length; i < l; i++) { dependencies[i](prune); } } this.dependencies = null; return true; } } }; Stream.wrap = function (value, Kind, param) { if (utils.isStream(value)) { return value; } else { return new Kind(value, param); } }; function makeLabel(label) { if (label === undefined) { return "(no label)"; } else { return label; } } exports['default'] = Stream; }); enifed('ember-metal/streams/subscriber', ['exports', 'ember-metal/merge'], function (exports, merge) { 'use strict'; function Subscriber(callback, context) { this.next = null; this.prev = null; this.callback = callback; this.context = context; } merge['default'](Subscriber.prototype, { removeFrom: function (stream) { var next = this.next; var prev = this.prev; if (prev) { prev.next = next; } else { stream.subscriberHead = next; } if (next) { next.prev = prev; } else { stream.subscriberTail = prev; } stream.maybeDeactivate(); } }); exports['default'] = Subscriber; }); enifed('ember-metal/streams/utils', ['exports', './stream'], function (exports, Stream) { 'use strict'; exports.isStream = isStream; exports.subscribe = subscribe; exports.unsubscribe = unsubscribe; exports.read = read; exports.readArray = readArray; exports.readHash = readHash; exports.scanArray = scanArray; exports.scanHash = scanHash; exports.concat = concat; exports.labelsFor = labelsFor; exports.labelsForObject = labelsForObject; exports.labelFor = labelFor; exports.or = or; exports.addDependency = addDependency; exports.zip = zip; exports.zipHash = zipHash; exports.chain = chain; exports.setValue = setValue; function isStream(object) { return object && object.isStream; } /* A method of subscribing to a stream which is safe for use with a non-stream object. If a non-stream object is passed, the function does nothing. @public @for Ember.stream @function subscribe @param {Object|Stream} object object or stream to potentially subscribe to @param {Function} callback function to run when stream value changes @param {Object} [context] the callback will be executed with this context if it is provided */ function subscribe(object, callback, context) { if (object && object.isStream) { return object.subscribe(callback, context); } } /* A method of unsubscribing from a stream which is safe for use with a non-stream object. If a non-stream object is passed, the function does nothing. @public @for Ember.stream @function unsubscribe @param {Object|Stream} object object or stream to potentially unsubscribe from @param {Function} callback function originally passed to `subscribe()` @param {Object} [context] object originally passed to `subscribe()` */ function unsubscribe(object, callback, context) { if (object && object.isStream) { object.unsubscribe(callback, context); } } /* Retrieve the value of a stream, or in the case a non-stream object is passed, return the object itself. @public @for Ember.stream @function read @param {Object|Stream} object object to return the value of @return the stream's current value, or the non-stream object itself */ function read(object) { if (object && object.isStream) { return object.value(); } else { return object; } } /* Map an array, replacing any streams with their values. @public @for Ember.stream @function readArray @param {Array} array The array to read values from @return {Array} a new array of the same length with the values of non-stream objects mapped from their original positions untouched, and the values of stream objects retaining their original position and replaced with the stream's current value. */ function readArray(array) { var length = array.length; var ret = new Array(length); for (var i = 0; i < length; i++) { ret[i] = read(array[i]); } return ret; } /* Map a hash, replacing any stream property values with the current value of that stream. @public @for Ember.stream @function readHash @param {Object} object The hash to read keys and values from @return {Object} a new object with the same keys as the passed object. The property values in the new object are the original values in the case of non-stream objects, and the streams' current values in the case of stream objects. */ function readHash(object) { var ret = {}; for (var key in object) { ret[key] = read(object[key]); } return ret; } /* Check whether an array contains any stream values @public @for Ember.stream @function scanArray @param {Array} array array given to a handlebars helper @return {Boolean} `true` if the array contains a stream/bound value, `false` otherwise */ function scanArray(array) { var length = array.length; var containsStream = false; for (var i = 0; i < length; i++) { if (isStream(array[i])) { containsStream = true; break; } } return containsStream; } /* Check whether a hash has any stream property values @public @for Ember.stream @function scanHash @param {Object} hash "hash" argument given to a handlebars helper @return {Boolean} `true` if the object contains a stream/bound value, `false` otherwise */ function scanHash(hash) { var containsStream = false; for (var prop in hash) { if (isStream(hash[prop])) { containsStream = true; break; } } return containsStream; } /* Join an array, with any streams replaced by their current values @public @for Ember.stream @function concat @param {Array} array An array containing zero or more stream objects and zero or more non-stream objects @param {String} separator string to be used to join array elements @return {String} String with array elements concatenated and joined by the provided separator, and any stream array members having been replaced by the current value of the stream */ function concat(array, separator) { // TODO: Create subclass ConcatStream < Stream. Defer // subscribing to streams until the value() is called. var hasStream = scanArray(array); if (hasStream) { var i, l; var stream = new Stream['default'](function () { return concat(readArray(array), separator); }, function () { var labels = labelsFor(array); return 'concat([' + labels.join(', ') + ']; separator=' + inspect(separator) + ')'; }); for (i = 0, l = array.length; i < l; i++) { subscribe(array[i], stream.notify, stream); } // used by angle bracket components to detect an attribute was provided // as a string literal stream.isConcat = true; return stream; } else { return array.join(separator); } } function labelsFor(streams) { var labels = []; for (var i = 0, l = streams.length; i < l; i++) { var stream = streams[i]; labels.push(labelFor(stream)); } return labels; } function labelsForObject(streams) { var labels = []; for (var prop in streams) { labels.push('' + prop + ': ' + inspect(streams[prop])); } return labels.length ? '{ ' + labels.join(', ') + ' }' : '{}'; } function labelFor(maybeStream) { if (isStream(maybeStream)) { var stream = maybeStream; return typeof stream.label === 'function' ? stream.label() : stream.label; } else { return inspect(maybeStream); } } function inspect(value) { switch (typeof value) { case 'string': return '"' + value + '"'; case 'object': return '{ ... }'; case 'function': return 'function() { ... }'; default: return String(value); } } function or(first, second) { var stream = new Stream['default'](function () { return first.value() || second.value(); }, function () { return '' + labelFor(first) + ' || ' + labelFor(second); }); stream.addDependency(first); stream.addDependency(second); return stream; } function addDependency(stream, dependency) { Ember.assert('Cannot add a stream as a dependency to a non-stream', isStream(stream) || !isStream(dependency)); if (isStream(stream)) { stream.addDependency(dependency); } } function zip(streams, callback, label) { Ember.assert('Must call zip with a label', !!label); var stream = new Stream['default'](function () { var array = readArray(streams); return callback ? callback(array) : array; }, function () { return '' + label + '(' + labelsFor(streams) + ')'; }); for (var i = 0, l = streams.length; i < l; i++) { stream.addDependency(streams[i]); } return stream; } function zipHash(object, callback, label) { Ember.assert('Must call zipHash with a label', !!label); var stream = new Stream['default'](function () { var hash = readHash(object); return callback ? callback(hash) : hash; }, function () { return '' + label + '(' + labelsForObject(object) + ')'; }); for (var prop in object) { stream.addDependency(object[prop]); } return stream; } /** Generate a new stream by providing a source stream and a function that can be used to transform the stream's value. In the case of a non-stream object, returns the result of the function. The value to transform would typically be available to the function you pass to `chain()` via scope. For example: ```javascript var source = ...; // stream returning a number // or a numeric (non-stream) object var result = chain(source, function() { var currentValue = read(source); return currentValue + 1; }); ``` In the example, result is a stream if source is a stream, or a number of source was numeric. @public @for Ember.stream @function chain @param {Object|Stream} value A stream or non-stream object @param {Function} fn function to be run when the stream value changes, or to be run once in the case of a non-stream object @return {Object|Stream} In the case of a stream `value` parameter, a new stream that will be updated with the return value of the provided function `fn`. In the case of a non-stream object, the return value of the provided function `fn`. */ function chain(value, fn, label) { Ember.assert('Must call chain with a label', !!label); if (isStream(value)) { var stream = new Stream['default'](fn, function () { return '' + label + '(' + labelFor(value) + ')'; }); stream.addDependency(value); return stream; } else { return fn(); } } function setValue(object, value) { if (object && object.isStream) { object.setValue(value); } } }); enifed('ember-metal/symbol', function () { 'use strict'; }); enifed('ember-metal/utils', ['exports', 'ember-metal/core', 'ember-metal/platform/create', 'ember-metal/platform/define_property'], function (exports, Ember, o_create, define_property) { exports.uuid = uuid; exports.symbol = symbol; exports.generateGuid = generateGuid; exports.guidFor = guidFor; exports.getMeta = getMeta; exports.setMeta = setMeta; exports.metaPath = metaPath; exports.wrap = wrap; exports.tryInvoke = tryInvoke; exports.makeArray = makeArray; exports.inspect = inspect; exports.apply = apply; exports.applyStr = applyStr; exports.meta = meta; exports.canInvoke = canInvoke; "REMOVE_USE_STRICT: true"; /** @module ember-metal */ /** Previously we used `Ember.$.uuid`, however `$.uuid` has been removed from jQuery master. We'll just bootstrap our own uuid now. @private @return {Number} the uuid */ var _uuid = 0; /** Generates a universally unique identifier. This method is used internally by Ember for assisting with the generation of GUID's and other unique identifiers such as `bind-attr` data attributes. @public @return {Number} [description] */ function uuid() { return ++_uuid; } /** Prefix used for guids through out Ember. @private @property GUID_PREFIX @for Ember @type String @final */ var GUID_PREFIX = "ember"; // Used for guid generation... var numberCache = []; var stringCache = {}; /** Strongly hint runtimes to intern the provided string. When do I need to use this function? For the most part, never. Pre-mature optimization is bad, and often the runtime does exactly what you need it to, and more often the trade-off isn't worth it. Why? Runtimes store strings in at least 2 different representations: Ropes and Symbols (interned strings). The Rope provides a memory efficient data-structure for strings created from concatenation or some other string manipulation like splitting. Unfortunately checking equality of different ropes can be quite costly as runtimes must resort to clever string comparison algorithms. These algorithms typically cost in proportion to the length of the string. Luckily, this is where the Symbols (interned strings) shine. As Symbols are unique by their string content, equality checks can be done by pointer comparison. How do I know if my string is a rope or symbol? Typically (warning general sweeping statement, but truthy in runtimes at present) static strings created as part of the JS source are interned. Strings often used for comparisons can be interned at runtime if some criteria are met. One of these criteria can be the size of the entire rope. For example, in chrome 38 a rope longer then 12 characters will not intern, nor will segments of that rope. Some numbers: http://jsperf.com/eval-vs-keys/8 Known Trick™ @private @return {String} interned version of the provided string */ function intern(str) { var obj = {}; obj[str] = 1; for (var key in obj) { if (key === str) { return key; } } return str; } function symbol(debugName) { // TODO: Investigate using platform symbols, but we do not // want to require non-enumerability for this API, which // would introduce a large cost. return intern(debugName + " [id=" + GUID_KEY + Math.floor(Math.random() * new Date()) + "]"); } /** A unique key used to assign guids and other private metadata to objects. If you inspect an object in your browser debugger you will often see these. They can be safely ignored. On browsers that support it, these properties are added with enumeration disabled so they won't show up when you iterate over your properties. @private @property GUID_KEY @for Ember @type String @final */ var GUID_KEY = intern("__ember" + +new Date()); var GUID_DESC = { writable: true, configurable: true, enumerable: false, value: null }; var undefinedDescriptor = { configurable: true, writable: true, enumerable: false, value: undefined }; var nullDescriptor = { configurable: true, writable: true, enumerable: false, value: null }; var META_DESC = { writable: true, configurable: true, enumerable: false, value: null }; var EMBER_META_PROPERTY = { name: "__ember_meta__", descriptor: META_DESC }; var GUID_KEY_PROPERTY = { name: GUID_KEY, descriptor: nullDescriptor }; var NEXT_SUPER_PROPERTY = { name: "__nextSuper", descriptor: undefinedDescriptor }; function generateGuid(obj, prefix) { if (!prefix) { prefix = GUID_PREFIX; } var ret = prefix + uuid(); if (obj) { if (obj[GUID_KEY] === null) { obj[GUID_KEY] = ret; } else { GUID_DESC.value = ret; if (obj.__defineNonEnumerable) { obj.__defineNonEnumerable(GUID_KEY_PROPERTY); } else { define_property.defineProperty(obj, GUID_KEY, GUID_DESC); } } } return ret; } /** Returns a unique id for the object. If the object does not yet have a guid, one will be assigned to it. You can call this on any object, `Ember.Object`-based or not, but be aware that it will add a `_guid` property. You can also use this method on DOM Element objects. @private @method guidFor @for Ember @param {Object} obj any object, string, number, Element, or primitive @return {String} the unique guid for this instance. */ function guidFor(obj) { // special cases where we don't want to add a key to object if (obj === undefined) { return "(undefined)"; } if (obj === null) { return "(null)"; } var ret; var type = typeof obj; // Don't allow prototype changes to String etc. to change the guidFor switch (type) { case "number": ret = numberCache[obj]; if (!ret) { ret = numberCache[obj] = "nu" + obj; } return ret; case "string": ret = stringCache[obj]; if (!ret) { ret = stringCache[obj] = "st" + uuid(); } return ret; case "boolean": return obj ? "(true)" : "(false)"; default: if (obj[GUID_KEY]) { return obj[GUID_KEY]; } if (obj === Object) { return "(Object)"; } if (obj === Array) { return "(Array)"; } ret = GUID_PREFIX + uuid(); if (obj[GUID_KEY] === null) { obj[GUID_KEY] = ret; } else { GUID_DESC.value = ret; if (obj.__defineNonEnumerable) { obj.__defineNonEnumerable(GUID_KEY_PROPERTY); } else { define_property.defineProperty(obj, GUID_KEY, GUID_DESC); } } return ret; } } // .......................................................... // META // function Meta(obj) { this.watching = {}; this.cache = undefined; this.cacheMeta = undefined; this.source = obj; this.deps = undefined; this.listeners = undefined; this.mixins = undefined; this.bindings = undefined; this.chains = undefined; this.values = undefined; this.proto = undefined; } Meta.prototype = { chainWatchers: null // FIXME }; if (!define_property.canDefineNonEnumerableProperties) { // on platforms that don't support enumerable false // make meta fail jQuery.isPlainObject() to hide from // jQuery.extend() by having a property that fails // hasOwnProperty check. Meta.prototype.__preventPlainObject__ = true; // Without non-enumerable properties, meta objects will be output in JSON // unless explicitly suppressed Meta.prototype.toJSON = function () {}; } // Placeholder for non-writable metas. var EMPTY_META = new Meta(null); if (define_property.hasPropertyAccessors) { EMPTY_META.values = {}; } /** Retrieves the meta hash for an object. If `writable` is true ensures the hash is writable for this object as well. The meta object contains information about computed property descriptors as well as any watched properties and other information. You generally will not access this information directly but instead work with higher level methods that manipulate this hash indirectly. @method meta @for Ember @private @param {Object} obj The object to retrieve meta for @param {Boolean} [writable=true] Pass `false` if you do not intend to modify the meta hash, allowing the method to avoid making an unnecessary copy. @return {Object} the meta hash for an object */ function meta(obj, writable) { var ret = obj.__ember_meta__; if (writable === false) { return ret || EMPTY_META; } if (!ret) { if (define_property.canDefineNonEnumerableProperties) { if (obj.__defineNonEnumerable) { obj.__defineNonEnumerable(EMBER_META_PROPERTY); } else { define_property.defineProperty(obj, "__ember_meta__", META_DESC); } } ret = new Meta(obj); if (define_property.hasPropertyAccessors) { ret.values = {}; } obj.__ember_meta__ = ret; } else if (ret.source !== obj) { if (obj.__defineNonEnumerable) { obj.__defineNonEnumerable(EMBER_META_PROPERTY); } else { define_property.defineProperty(obj, "__ember_meta__", META_DESC); } ret = o_create['default'](ret); ret.watching = o_create['default'](ret.watching); ret.cache = undefined; ret.cacheMeta = undefined; ret.source = obj; if (define_property.hasPropertyAccessors) { ret.values = o_create['default'](ret.values); } obj["__ember_meta__"] = ret; } return ret; } function getMeta(obj, property) { var _meta = meta(obj, false); return _meta[property]; } function setMeta(obj, property, value) { var _meta = meta(obj, true); _meta[property] = value; return value; } /** @deprecated @private In order to store defaults for a class, a prototype may need to create a default meta object, which will be inherited by any objects instantiated from the class's constructor. However, the properties of that meta object are only shallow-cloned, so if a property is a hash (like the event system's `listeners` hash), it will by default be shared across all instances of that class. This method allows extensions to deeply clone a series of nested hashes or other complex objects. For instance, the event system might pass `['listeners', 'foo:change', 'ember157']` to `prepareMetaPath`, which will walk down the keys provided. For each key, if the key does not exist, it is created. If it already exists and it was inherited from its constructor, the constructor's key is cloned. You can also pass false for `writable`, which will simply return undefined if `prepareMetaPath` discovers any part of the path that shared or undefined. @method metaPath @for Ember @param {Object} obj The object whose meta we are examining @param {Array} path An array of keys to walk down @param {Boolean} writable whether or not to create a new meta (or meta property) if one does not already exist or if it's shared with its constructor */ function metaPath(obj, path, writable) { Ember['default'].deprecate("Ember.metaPath is deprecated and will be removed from future releases."); var _meta = meta(obj, writable); var keyName, value; for (var i = 0, l = path.length; i < l; i++) { keyName = path[i]; value = _meta[keyName]; if (!value) { if (!writable) { return undefined; } value = _meta[keyName] = { __ember_source__: obj }; } else if (value.__ember_source__ !== obj) { if (!writable) { return undefined; } value = _meta[keyName] = o_create['default'](value); value.__ember_source__ = obj; } _meta = value; } return value; } /** Wraps the passed function so that `this._super` will point to the superFunc when the function is invoked. This is the primitive we use to implement calls to super. @private @method wrap @for Ember @param {Function} func The function to call @param {Function} superFunc The super function. @return {Function} wrapped function. */ function wrap(func, superFunc) { function superWrapper() { var ret; var sup = this && this.__nextSuper; var length = arguments.length; if (this) { this.__nextSuper = superFunc; } if (length === 0) { ret = func.call(this); } else if (length === 1) { ret = func.call(this, arguments[0]); } else if (length === 2) { ret = func.call(this, arguments[0], arguments[1]); } else { var args = new Array(length); for (var i = 0; i < length; i++) { args[i] = arguments[i]; } ret = apply(this, func, args); } if (this) { this.__nextSuper = sup; } return ret; } superWrapper.wrappedFunction = func; superWrapper.__ember_observes__ = func.__ember_observes__; superWrapper.__ember_observesBefore__ = func.__ember_observesBefore__; superWrapper.__ember_listens__ = func.__ember_listens__; return superWrapper; } /** Checks to see if the `methodName` exists on the `obj`. ```javascript var foo = { bar: function() { return 'bar'; }, baz: null }; Ember.canInvoke(foo, 'bar'); // true Ember.canInvoke(foo, 'baz'); // false Ember.canInvoke(foo, 'bat'); // false ``` @method canInvoke @for Ember @param {Object} obj The object to check for the method @param {String} methodName The method name to check for @return {Boolean} */ function canInvoke(obj, methodName) { return !!(obj && typeof obj[methodName] === "function"); } /** Checks to see if the `methodName` exists on the `obj`, and if it does, invokes it with the arguments passed. ```javascript var d = new Date('03/15/2013'); Ember.tryInvoke(d, 'getTime'); // 1363320000000 Ember.tryInvoke(d, 'setFullYear', [2014]); // 1394856000000 Ember.tryInvoke(d, 'noSuchMethod', [2014]); // undefined ``` @method tryInvoke @for Ember @param {Object} obj The object to check for the method @param {String} methodName The method name to check for @param {Array} [args] The arguments to pass to the method @return {*} the return value of the invoked method or undefined if it cannot be invoked */ function tryInvoke(obj, methodName, args) { if (canInvoke(obj, methodName)) { return args ? applyStr(obj, methodName, args) : applyStr(obj, methodName); } } // https://github.com/emberjs/ember.js/pull/1617 var needsFinallyFix = (function () { var count = 0; try { // jscs:disable try {} finally { count++; throw new Error("needsFinallyFixTest"); } // jscs:enable } catch (e) {} return count !== 1; })(); /** Provides try/finally functionality, while working around Safari's double finally bug. ```javascript var tryable = function() { someResource.lock(); runCallback(); // May throw error. }; var finalizer = function() { someResource.unlock(); }; Ember.tryFinally(tryable, finalizer); ``` @method tryFinally @deprecated Use JavaScript's native try/finally @for Ember @param {Function} tryable The function to run the try callback @param {Function} finalizer The function to run the finally callback @param {Object} [binding] The optional calling object. Defaults to 'this' @return {*} The return value is the that of the finalizer, unless that value is undefined, in which case it is the return value of the tryable */ var tryFinally; if (needsFinallyFix) { tryFinally = function (tryable, finalizer, binding) { var result, finalResult, finalError; binding = binding || this; try { result = tryable.call(binding); } finally { try { finalResult = finalizer.call(binding); } catch (e) { finalError = e; } } if (finalError) { throw finalError; } return finalResult === undefined ? result : finalResult; }; } else { tryFinally = function (tryable, finalizer, binding) { var result, finalResult; binding = binding || this; try { result = tryable.call(binding); } finally { finalResult = finalizer.call(binding); } return finalResult === undefined ? result : finalResult; }; } var deprecatedTryFinally = function () { Ember['default'].deprecate("tryFinally is deprecated. Please use JavaScript's native try/finally.", false); return tryFinally.apply(this, arguments); }; /** Provides try/catch/finally functionality, while working around Safari's double finally bug. ```javascript var tryable = function() { for (i = 0, l = listeners.length; i < l; i++) { listener = listeners[i]; beforeValues[i] = listener.before(name, time(), payload); } return callback.call(binding); }; var catchable = function(e) { payload = payload || {}; payload.exception = e; }; var finalizer = function() { for (i = 0, l = listeners.length; i < l; i++) { listener = listeners[i]; listener.after(name, time(), payload, beforeValues[i]); } }; Ember.tryCatchFinally(tryable, catchable, finalizer); ``` @method tryCatchFinally @deprecated Use JavaScript's native try/catch/finally instead @for Ember @param {Function} tryable The function to run the try callback @param {Function} catchable The function to run the catchable callback @param {Function} finalizer The function to run the finally callback @param {Object} [binding] The optional calling object. Defaults to 'this' @return {*} The return value is the that of the finalizer, unless that value is undefined, in which case it is the return value of the tryable. */ var tryCatchFinally; if (needsFinallyFix) { tryCatchFinally = function (tryable, catchable, finalizer, binding) { var result, finalResult, finalError; binding = binding || this; try { result = tryable.call(binding); } catch (error) { result = catchable.call(binding, error); } finally { try { finalResult = finalizer.call(binding); } catch (e) { finalError = e; } } if (finalError) { throw finalError; } return finalResult === undefined ? result : finalResult; }; } else { tryCatchFinally = function (tryable, catchable, finalizer, binding) { var result, finalResult; binding = binding || this; try { result = tryable.call(binding); } catch (error) { result = catchable.call(binding, error); } finally { finalResult = finalizer.call(binding); } return finalResult === undefined ? result : finalResult; }; } var deprecatedTryCatchFinally = function () { Ember['default'].deprecate("tryCatchFinally is deprecated. Please use JavaScript's native try/catch/finally.", false); return tryCatchFinally.apply(this, arguments); }; // ........................................ // TYPING & ARRAY MESSAGING // var toString = Object.prototype.toString; var isArray = Array.isArray || function (value) { return value !== null && value !== undefined && typeof value === "object" && typeof value.length === "number" && toString.call(value) === "[object Array]"; }; /** Forces the passed object to be part of an array. If the object is already an array, it will return the object. Otherwise, it will add the object to an array. If obj is `null` or `undefined`, it will return an empty array. ```javascript Ember.makeArray(); // [] Ember.makeArray(null); // [] Ember.makeArray(undefined); // [] Ember.makeArray('lindsay'); // ['lindsay'] Ember.makeArray([1, 2, 42]); // [1, 2, 42] var controller = Ember.ArrayProxy.create({ content: [] }); Ember.makeArray(controller) === controller; // true ``` @method makeArray @for Ember @param {Object} obj the object @return {Array} */ function makeArray(obj) { if (obj === null || obj === undefined) { return []; } return isArray(obj) ? obj : [obj]; } /** Convenience method to inspect an object. This method will attempt to convert the object into a useful string description. It is a pretty simple implementation. If you want something more robust, use something like JSDump: https://github.com/NV/jsDump @method inspect @for Ember @param {Object} obj The object you want to inspect. @return {String} A description of the object @since 1.4.0 */ function inspect(obj) { if (obj === null) { return "null"; } if (obj === undefined) { return "undefined"; } if (isArray(obj)) { return "[" + obj + "]"; } // for non objects if (typeof obj !== "object") { return "" + obj; } // overridden toString if (typeof obj.toString === "function" && obj.toString !== toString) { return obj.toString(); } // Object.prototype.toString === {}.toString var v; var ret = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { v = obj[key]; if (v === "toString") { continue; } // ignore useless items if (typeof v === "function") { v = "function() { ... }"; } if (v && typeof v.toString !== "function") { ret.push(key + ": " + toString.call(v)); } else { ret.push(key + ": " + v); } } } return "{" + ret.join(", ") + "}"; } // The following functions are intentionally minified to keep the functions // below Chrome's function body size inlining limit of 600 chars. /** @param {Object} target @param {Function} method @param {Array} args */ function apply(t, m, a) { var l = a && a.length; if (!a || !l) { return m.call(t); } switch (l) { case 1: return m.call(t, a[0]); case 2: return m.call(t, a[0], a[1]); case 3: return m.call(t, a[0], a[1], a[2]); case 4: return m.call(t, a[0], a[1], a[2], a[3]); case 5: return m.call(t, a[0], a[1], a[2], a[3], a[4]); default: return m.apply(t, a); } } /** @param {Object} target @param {String} method @param {Array} args */ function applyStr(t, m, a) { var l = a && a.length; if (!a || !l) { return t[m](); } switch (l) { case 1: return t[m](a[0]); case 2: return t[m](a[0], a[1]); case 3: return t[m](a[0], a[1], a[2]); case 4: return t[m](a[0], a[1], a[2], a[3]); case 5: return t[m](a[0], a[1], a[2], a[3], a[4]); default: return t[m].apply(t, a); } } exports.GUID_DESC = GUID_DESC; exports.EMBER_META_PROPERTY = EMBER_META_PROPERTY; exports.GUID_KEY_PROPERTY = GUID_KEY_PROPERTY; exports.NEXT_SUPER_PROPERTY = NEXT_SUPER_PROPERTY; exports.GUID_KEY = GUID_KEY; exports.META_DESC = META_DESC; exports.EMPTY_META = EMPTY_META; exports.isArray = isArray; exports.tryCatchFinally = tryCatchFinally; exports.deprecatedTryCatchFinally = deprecatedTryCatchFinally; exports.tryFinally = tryFinally; exports.deprecatedTryFinally = deprecatedTryFinally; }); enifed('ember-metal/watch_key', ['exports', 'ember-metal/core', 'ember-metal/utils', 'ember-metal/platform/define_property', 'ember-metal/properties'], function (exports, Ember, utils, define_property, properties) { 'use strict'; exports.watchKey = watchKey; exports.unwatchKey = unwatchKey; function watchKey(obj, keyName, meta) { // can't watch length on Array - it is special... if (keyName === "length" && utils.isArray(obj)) { return; } var m = meta || utils.meta(obj); var watching = m.watching; // activate watching first time if (!watching[keyName]) { watching[keyName] = 1; var possibleDesc = obj[keyName]; var desc = possibleDesc !== null && typeof possibleDesc === "object" && possibleDesc.isDescriptor ? possibleDesc : undefined; if (desc && desc.willWatch) { desc.willWatch(obj, keyName); } if ("function" === typeof obj.willWatchProperty) { obj.willWatchProperty(keyName); } if (define_property.hasPropertyAccessors) { handleMandatorySetter(m, obj, keyName); } } else { watching[keyName] = (watching[keyName] || 0) + 1; } } var handleMandatorySetter = function handleMandatorySetter(m, obj, keyName) { var descriptor = Object.getOwnPropertyDescriptor && Object.getOwnPropertyDescriptor(obj, keyName); var configurable = descriptor ? descriptor.configurable : true; var isWritable = descriptor ? descriptor.writable : true; var hasValue = descriptor ? "value" in descriptor : true; var possibleDesc = descriptor && descriptor.value; var isDescriptor = possibleDesc !== null && typeof possibleDesc === "object" && possibleDesc.isDescriptor; if (isDescriptor) { return; } // this x in Y deopts, so keeping it in this function is better; if (configurable && isWritable && hasValue && keyName in obj) { m.values[keyName] = obj[keyName]; define_property.defineProperty(obj, keyName, { configurable: true, enumerable: Object.prototype.propertyIsEnumerable.call(obj, keyName), set: properties.MANDATORY_SETTER_FUNCTION(keyName), get: properties.DEFAULT_GETTER_FUNCTION(keyName) }); } }; // This is super annoying, but required until // https://github.com/babel/babel/issues/906 is resolved ; // jshint ignore:line function unwatchKey(obj, keyName, meta) { var m = meta || utils.meta(obj); var watching = m.watching; if (watching[keyName] === 1) { watching[keyName] = 0; var possibleDesc = obj[keyName]; var desc = possibleDesc !== null && typeof possibleDesc === "object" && possibleDesc.isDescriptor ? possibleDesc : undefined; if (desc && desc.didUnwatch) { desc.didUnwatch(obj, keyName); } if ("function" === typeof obj.didUnwatchProperty) { obj.didUnwatchProperty(keyName); } if (!desc && define_property.hasPropertyAccessors && keyName in obj) { define_property.defineProperty(obj, keyName, { configurable: true, enumerable: Object.prototype.propertyIsEnumerable.call(obj, keyName), set: function (val) { // redefine to set as enumerable define_property.defineProperty(obj, keyName, { configurable: true, writable: true, enumerable: true, value: val }); delete m.values[keyName]; }, get: properties.DEFAULT_GETTER_FUNCTION(keyName) }); } } else if (watching[keyName] > 1) { watching[keyName]--; } } }); enifed('ember-metal/watch_path', ['exports', 'ember-metal/utils', 'ember-metal/chains'], function (exports, utils, chains) { 'use strict'; exports.watchPath = watchPath; exports.unwatchPath = unwatchPath; function chainsFor(obj, meta) { var m = meta || utils.meta(obj); var ret = m.chains; if (!ret) { ret = m.chains = new chains.ChainNode(null, null, obj); } else if (ret.value() !== obj) { ret = m.chains = ret.copy(obj); } return ret; } function watchPath(obj, keyPath, meta) { // can't watch length on Array - it is special... if (keyPath === "length" && utils.isArray(obj)) { return; } var m = meta || utils.meta(obj); var watching = m.watching; if (!watching[keyPath]) { // activate watching first time watching[keyPath] = 1; chainsFor(obj, m).add(keyPath); } else { watching[keyPath] = (watching[keyPath] || 0) + 1; } } function unwatchPath(obj, keyPath, meta) { var m = meta || utils.meta(obj); var watching = m.watching; if (watching[keyPath] === 1) { watching[keyPath] = 0; chainsFor(obj, m).remove(keyPath); } else if (watching[keyPath] > 1) { watching[keyPath]--; } } }); enifed('ember-metal/watching', ['exports', 'ember-metal/utils', 'ember-metal/chains', 'ember-metal/watch_key', 'ember-metal/watch_path', 'ember-metal/path_cache'], function (exports, utils, chains, watch_key, watch_path, path_cache) { 'use strict'; exports.isWatching = isWatching; exports.unwatch = unwatch; exports.destroy = destroy; exports.watch = watch; function watch(obj, _keyPath, m) { // can't watch length on Array - it is special... if (_keyPath === "length" && utils.isArray(obj)) { return; } if (!path_cache.isPath(_keyPath)) { watch_key.watchKey(obj, _keyPath, m); } else { watch_path.watchPath(obj, _keyPath, m); } } function isWatching(obj, key) { var meta = obj["__ember_meta__"]; return (meta && meta.watching[key]) > 0; } watch.flushPending = chains.flushPendingChains; function unwatch(obj, _keyPath, m) { // can't watch length on Array - it is special... if (_keyPath === "length" && utils.isArray(obj)) { return; } if (!path_cache.isPath(_keyPath)) { watch_key.unwatchKey(obj, _keyPath, m); } else { watch_path.unwatchPath(obj, _keyPath, m); } } var NODE_STACK = []; /** Tears down the meta on an object so that it can be garbage collected. Multiple calls will have no effect. @method destroy @for Ember @param {Object} obj the object to destroy @return {void} */ function destroy(obj) { var meta = obj["__ember_meta__"]; var node, nodes, key, nodeObject; if (meta) { obj["__ember_meta__"] = null; // remove chainWatchers to remove circular references that would prevent GC node = meta.chains; if (node) { NODE_STACK.push(node); // process tree while (NODE_STACK.length > 0) { node = NODE_STACK.pop(); // push children nodes = node._chains; if (nodes) { for (key in nodes) { if (nodes.hasOwnProperty(key)) { NODE_STACK.push(nodes[key]); } } } // remove chainWatcher in node object if (node._watching) { nodeObject = node._object; if (nodeObject) { chains.removeChainWatcher(nodeObject, node._key, node); } } } } } } }); enifed('ember-routing-htmlbars', ['exports', 'ember-metal/core', 'ember-metal/merge', 'ember-htmlbars/helpers', 'ember-htmlbars/keywords', 'ember-routing-htmlbars/helpers/query-params', 'ember-routing-htmlbars/keywords/action', 'ember-routing-htmlbars/keywords/element-action', 'ember-routing-htmlbars/keywords/link-to', 'ember-routing-htmlbars/keywords/render'], function (exports, Ember, merge, helpers, keywords, query_params, action, elementAction, linkTo, render) { 'use strict'; /** Ember Routing HTMLBars Helpers @module ember @submodule ember-routing-htmlbars @requires ember-routing */ helpers.registerHelper("query-params", query_params.queryParamsHelper); keywords.registerKeyword("action", action['default']); keywords.registerKeyword("@element_action", elementAction['default']); keywords.registerKeyword("link-to", linkTo['default']); keywords.registerKeyword("render", render['default']); var deprecatedLinkTo = merge['default']({}, linkTo['default']); merge['default'](deprecatedLinkTo, { link: function (state, params, hash) { linkTo['default'].link.call(this, state, params, hash); Ember['default'].deprecate("The 'linkTo' view helper is deprecated in favor of 'link-to'"); } }); keywords.registerKeyword("linkTo", deprecatedLinkTo); exports['default'] = Ember['default']; }); enifed('ember-routing-htmlbars/helpers/query-params', ['exports', 'ember-metal/core', 'ember-routing/system/query_params'], function (exports, Ember, QueryParams) { 'use strict'; exports.queryParamsHelper = queryParamsHelper; function queryParamsHelper(params, hash) { Ember['default'].assert("The `query-params` helper only accepts hash parameters, e.g. (query-params queryParamPropertyName='foo') as opposed to just (query-params 'foo')", params.length === 0); return QueryParams['default'].create({ values: hash }); } }); enifed('ember-routing-htmlbars/keywords/action', ['exports', 'htmlbars-runtime/hooks', 'ember-routing-htmlbars/keywords/closure-action'], function (exports, hooks, closureAction) { 'use strict'; /** @module ember @submodule ember-htmlbars */ exports['default'] = function (morph, env, scope, params, hash, template, inverse, visitor) { if (morph) { hooks.keyword("@element_action", morph, env, scope, params, hash, template, inverse, visitor); return true; } return closureAction['default'](morph, env, scope, params, hash, template, inverse, visitor); } }); enifed('ember-routing-htmlbars/keywords/closure-action', ['exports', 'ember-metal/streams/stream', 'ember-metal/array', 'ember-metal/streams/utils', 'ember-metal/keys', 'ember-metal/utils', 'ember-metal/property_get'], function (exports, Stream, array, utils, keys, ember_metal__utils, property_get) { 'use strict'; exports['default'] = closureAction; var INVOKE = ember_metal__utils.symbol("INVOKE"); var ACTION = ember_metal__utils.symbol("ACTION");function closureAction(morph, env, scope, params, hash, template, inverse, visitor) { return new Stream['default'](function () { var _this = this; array.map.call(params, this.addDependency, this); array.map.call(keys['default'](hash), function (item) { _this.addDependency(item); }); var rawAction = params[0]; var actionArguments = utils.readArray(params.slice(1, params.length)); var target, action, valuePath; if (rawAction[INVOKE]) { // on-change={{action (mut name)}} target = rawAction; action = rawAction[INVOKE]; } else { // on-change={{action setName}} // element-space actions look to "controller" then target. Here we only // look to "target". target = utils.read(scope.self); action = utils.read(rawAction); if (typeof action === "string") { // on-change={{action 'setName'}} if (hash.target) { // on-change={{action 'setName' target=alternativeComponent}} target = utils.read(hash.target); } if (target.actions) { action = target.actions[action]; } else { action = target._actions[action]; } } } if (hash.value) { // ``` Components must have a `-` in their name to avoid conflicts with built-in controls that wrap HTML elements. This is consistent with the same requirement in web components. @class Component @namespace Ember @extends Ember.View */ var Component = View['default'].extend(TargetActionSupport['default'], ComponentTemplateDeprecation['default'], { /* This is set so that the proto inspection in appendTemplatedView does not think that it should set the components `context` to that of the parent view. */ controller: null, context: null, instrumentName: "component", instrumentDisplay: computed.computed(function () { if (this._debugContainerKey) { return "{{" + this._debugContainerKey.split(":")[1] + "}}"; } }), init: function () { this._super.apply(this, arguments); property_set.set(this, "controller", this); property_set.set(this, "context", this); }, /** A components template property is set by passing a block during its invocation. It is executed within the parent context. Example: ```handlebars {{#my-component}} // something that is run in the context // of the parent context {{/my-component}} ``` Specifying a template directly to a component is deprecated without also specifying the layout property. @deprecated @property template */ template: computed.computed("templateName", { get: function () { var templateName = property_get.get(this, "templateName"); var template = this.templateForName(templateName, "template"); Ember['default'].assert("You specified the templateName " + templateName + " for " + this + ", but it did not exist.", !templateName || !!template); return template || property_get.get(this, "defaultTemplate"); }, set: function (key, value) { return value; } }), /** Specifying a components `templateName` is deprecated without also providing the `layout` or `layoutName` properties. @deprecated @property templateName */ templateName: null, /** If the component is currently inserted into the DOM of a parent view, this property will point to the controller of the parent view. @property targetObject @type Ember.Controller @default null */ targetObject: computed.computed("controller", function (key) { if (this._targetObject) { return this._targetObject; } if (this._controller) { return this._controller; } var parentView = property_get.get(this, "parentView"); return parentView ? property_get.get(parentView, "controller") : null; }), /** Triggers a named action on the controller context where the component is used if this controller has registered for notifications of the action. For example a component for playing or pausing music may translate click events into action notifications of "play" or "stop" depending on some internal state of the component: ```javascript App.PlayButtonComponent = Ember.Component.extend({ click: function() { if (this.get('isPlaying')) { this.sendAction('play'); } else { this.sendAction('stop'); } } }); ``` When used inside a template these component actions are configured to trigger actions in the outer application context: ```handlebars {{! application.hbs }} {{play-button play="musicStarted" stop="musicStopped"}} ``` When the component receives a browser `click` event it translate this interaction into application-specific semantics ("play" or "stop") and triggers the specified action name on the controller for the template where the component is used: ```javascript App.ApplicationController = Ember.Controller.extend({ actions: { musicStarted: function() { // called when the play button is clicked // and the music started playing }, musicStopped: function() { // called when the play button is clicked // and the music stopped playing } } }); ``` If no action name is passed to `sendAction` a default name of "action" is assumed. ```javascript App.NextButtonComponent = Ember.Component.extend({ click: function() { this.sendAction(); } }); ``` ```handlebars {{! application.hbs }} {{next-button action="playNextSongInAlbum"}} ``` ```javascript App.ApplicationController = Ember.Controller.extend({ actions: { playNextSongInAlbum: function() { ... } } }); ``` @method sendAction @param [action] {String} the action to trigger @param [context] {*} a context to send with the action */ sendAction: function (action) { for (var _len = arguments.length, contexts = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { contexts[_key - 1] = arguments[_key]; } var actionName; // Send the default action if (action === undefined) { action = "action"; } actionName = property_get.get(this, "attrs." + action) || property_get.get(this, action); actionName = validateAction(this, actionName); // If no action name for that action could be found, just abort. if (actionName === undefined) { return; } if (typeof actionName === "function") { actionName.apply(null, contexts); } else { this.triggerAction({ action: actionName, actionContext: contexts }); } }, send: function (actionName) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } var target; var hasAction = this._actions && this._actions[actionName]; if (hasAction) { var shouldBubble = this._actions[actionName].apply(this, args) === true; if (!shouldBubble) { return; } } if (target = property_get.get(this, "target")) { Ember['default'].assert("The `target` for " + this + " (" + target + ") does not have a `send` method", typeof target.send === "function"); target.send.apply(target, arguments); } else { if (!hasAction) { throw new Error(Ember['default'].inspect(this) + " had no action handler for: " + actionName); } } } /** Returns true when the component was invoked with a block template. Example (`hasBlock` will be `false`): ```hbs {{! templates/application.hbs }} {{foo-bar}} {{! templates/components/foo-bar.js }} {{#if hasBlock}} This will not be printed, because no block was provided {{/if}} ``` Example (`hasBlock` will be `true`): ```hbs {{! templates/application.hbs }} {{#foo-bar}} Hi! {{/foo-bar}} {{! templates/components/foo-bar.js }} {{#if hasBlock}} This will be printed because a block was provided {{yield}} {{/if}} ``` @public @property hasBlock @returns Boolean */ /** Returns true when the component was invoked with a block parameter supplied. Example (`hasBlockParams` will be `false`): ```hbs {{! templates/application.hbs }} {{#foo-bar}} No block parameter. {{/foo-bar}} {{! templates/components/foo-bar.js }} {{#if hasBlockParams}} This will not be printed, because no block was provided {{yield this}} {{/if}} ``` Example (`hasBlockParams` will be `true`): ```hbs {{! templates/application.hbs }} {{#foo-bar as |foo|}} Hi! {{/foo-bar}} {{! templates/components/foo-bar.js }} {{#if hasBlockParams}} This will be printed because a block was provided {{yield this}} {{/if}} ``` @public @property hasBlockParams @returns Boolean */ }); Component.reopenClass({ isComponentFactory: true }); exports['default'] = Component; }); enifed('ember-views/views/container_view', ['exports', 'ember-metal/core', 'ember-runtime/mixins/mutable_array', 'ember-views/views/view', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/enumerable_utils', 'ember-metal/mixin', 'ember-htmlbars/templates/container-view'], function (exports, Ember, MutableArray, View, property_get, property_set, enumerable_utils, mixin, containerViewTemplate) { 'use strict'; containerViewTemplate['default'].meta.revision = "Ember@1.13.0-beta.2"; /** @module ember @submodule ember-views */ /** A `ContainerView` is an `Ember.View` subclass that implements `Ember.MutableArray` allowing programmatic management of its child views. ## Setting Initial Child Views The initial array of child views can be set in one of two ways. You can provide a `childViews` property at creation time that contains instance of `Ember.View`: ```javascript aContainer = Ember.ContainerView.create({ childViews: [Ember.View.create(), Ember.View.create()] }); ``` You can also provide a list of property names whose values are instances of `Ember.View`: ```javascript aContainer = Ember.ContainerView.create({ childViews: ['aView', 'bView', 'cView'], aView: Ember.View.create(), bView: Ember.View.create(), cView: Ember.View.create() }); ``` The two strategies can be combined: ```javascript aContainer = Ember.ContainerView.create({ childViews: ['aView', Ember.View.create()], aView: Ember.View.create() }); ``` Each child view's rendering will be inserted into the container's rendered HTML in the same order as its position in the `childViews` property. ## Adding and Removing Child Views The container view implements `Ember.MutableArray` allowing programmatic management of its child views. To remove a view, pass that view into a `removeObject` call on the container view. Given an empty `` the following code ```javascript aContainer = Ember.ContainerView.create({ classNames: ['the-container'], childViews: ['aView', 'bView'], aView: Ember.View.create({ template: Ember.Handlebars.compile("A") }), bView: Ember.View.create({ template: Ember.Handlebars.compile("B") }) }); aContainer.appendTo('body'); ``` Results in the HTML ```html
A
B
``` Removing a view ```javascript aContainer.toArray(); // [aContainer.aView, aContainer.bView] aContainer.removeObject(aContainer.get('bView')); aContainer.toArray(); // [aContainer.aView] ``` Will result in the following HTML ```html
A
``` Similarly, adding a child view is accomplished by adding `Ember.View` instances to the container view. Given an empty `` the following code ```javascript aContainer = Ember.ContainerView.create({ classNames: ['the-container'], childViews: ['aView', 'bView'], aView: Ember.View.create({ template: Ember.Handlebars.compile("A") }), bView: Ember.View.create({ template: Ember.Handlebars.compile("B") }) }); aContainer.appendTo('body'); ``` Results in the HTML ```html
A
B
``` Adding a view ```javascript AnotherViewClass = Ember.View.extend({ template: Ember.Handlebars.compile("Another view") }); aContainer.toArray(); // [aContainer.aView, aContainer.bView] aContainer.pushObject(AnotherViewClass.create()); aContainer.toArray(); // [aContainer.aView, aContainer.bView, ] ``` Will result in the following HTML ```html
A
B
Another view
``` ## Templates and Layout A `template`, `templateName`, `defaultTemplate`, `layout`, `layoutName` or `defaultLayout` property on a container view will not result in the template or layout being rendered. The HTML contents of a `Ember.ContainerView`'s DOM representation will only be the rendered HTML of its child views. @class ContainerView @namespace Ember @extends Ember.View */ var ContainerView = View['default'].extend(MutableArray['default'], { willWatchProperty: function (prop) { Ember['default'].deprecate("ContainerViews should not be observed as arrays. This behavior will change in future implementations of ContainerView.", !prop.match(/\[]/) && prop.indexOf("@") !== 0); }, init: function () { this._super.apply(this, arguments); var userChildViews = property_get.get(this, "childViews"); Ember['default'].deprecate("Setting `childViews` on a Container is deprecated.", Ember['default'].isEmpty(userChildViews)); // redefine view's childViews property that was obliterated // 2.0TODO: Don't Ember.A() this so users disabling prototype extensions // don't pay a penalty. var childViews = this.childViews = Ember['default'].A([]); enumerable_utils.forEach(userChildViews, function (viewName, idx) { var view; if ("string" === typeof viewName) { view = property_get.get(this, viewName); view = this.createChildView(view); property_set.set(this, viewName, view); } else { view = this.createChildView(viewName); } childViews[idx] = view; }, this); var currentView = property_get.get(this, "currentView"); if (currentView) { if (!childViews.length) { childViews = this.childViews = Ember['default'].A(this.childViews.slice()); } childViews.push(this.createChildView(currentView)); } property_set.set(this, "length", childViews.length); }, // Normally parentView and childViews are managed at render time. However, // the ContainerView is an unusual legacy case. People expect to be able to // push a child view into the ContainerView and have its parentView set // appropriately. As a result, we link the child nodes ahead of time and // ignore render-time linking. appendChild: function (view) { // This occurs if the view being appended is the empty view, rather than // a view eagerly inserted into the childViews array. if (view.parentView !== this) { this.linkChild(view); } }, _currentViewWillChange: mixin.beforeObserver("currentView", function () { var currentView = property_get.get(this, "currentView"); if (currentView) { currentView.destroy(); } }), _currentViewDidChange: mixin.observer("currentView", function () { var currentView = property_get.get(this, "currentView"); if (currentView) { Ember['default'].assert("You tried to set a current view that already has a parent. Make sure you don't have multiple outlets in the same view.", !currentView.parentView); this.pushObject(currentView); } }), layout: containerViewTemplate['default'], replace: function (idx, removedCount) { var _this = this; var addedViews = arguments[2] === undefined ? [] : arguments[2]; var addedCount = property_get.get(addedViews, "length"); var childViews = property_get.get(this, "childViews"); Ember['default'].assert("You can't add a child to a container - the child is already a child of another view", function () { for (var i = 0, l = addedViews.length; i < l; i++) { var item = addedViews[i]; if (item.parentView && item.parentView !== _this) { return false; } } return true; }); this.arrayContentWillChange(idx, removedCount, addedCount); // Normally parentView and childViews are managed at render time. However, // the ContainerView is an unusual legacy case. People expect to be able to // push a child view into the ContainerView and have its parentView set // appropriately. // // Because of this, we synchronously fix up the parentView/childViews tree // as soon as views are added or removed, despite the fact that this will // happen automatically when we render. var removedViews = childViews.slice(idx, idx + removedCount); enumerable_utils.forEach(removedViews, function (view) { return _this.unlinkChild(view); }); enumerable_utils.forEach(addedViews, function (view) { return _this.linkChild(view); }); childViews.splice.apply(childViews, [idx, removedCount].concat(addedViews)); this.notifyPropertyChange("childViews"); this.arrayContentDidChange(idx, removedCount, addedCount); //Ember.assert("You can't add a child to a container - the child is already a child of another view", emberA(addedViews).every(function(item) { return !item.parentView || item.parentView === self; })); property_set.set(this, "length", childViews.length); return this; }, objectAt: function (idx) { return property_get.get(this, "childViews")[idx]; } }); exports['default'] = ContainerView; }); enifed('ember-views/views/core_view', ['exports', 'ember-metal-views/renderer', 'ember-views/views/states', 'ember-runtime/system/object', 'ember-runtime/mixins/evented', 'ember-runtime/mixins/action_handler', 'ember-metal/property_get', 'ember-runtime/utils', 'htmlbars-runtime'], function (exports, Renderer, states, EmberObject, Evented, ActionHandler, property_get, utils, htmlbars_runtime) { 'use strict'; function K() { return this; } // Normally, the renderer is injected by the container when the view is looked // up. However, if someone creates a view without looking it up via the // container (e.g. `Ember.View.create().append()`) then we create a fallback // DOM renderer that is shared. In general, this path should be avoided since // views created this way cannot run in a node environment. var renderer; /** `Ember.CoreView` is an abstract class that exists to give view-like behavior to both Ember's main view class `Ember.View` and other classes that don't need the fully functionaltiy of `Ember.View`. Unless you have specific needs for `CoreView`, you will use `Ember.View` in your applications. @class CoreView @namespace Ember @extends Ember.Object @deprecated Use `Ember.View` instead. @uses Ember.Evented @uses Ember.ActionHandler */ var CoreView = EmberObject['default'].extend(Evented['default'], ActionHandler['default'], { isView: true, _states: states.cloneStates(states.states), init: function () { this._super.apply(this, arguments); this._state = "preRender"; this.currentState = this._states.preRender; this._isVisible = property_get.get(this, "isVisible"); // Fallback for legacy cases where the view was created directly // via `create()` instead of going through the container. if (!this.renderer) { var DOMHelper = domHelper(); renderer = renderer || new Renderer['default'](new DOMHelper()); this.renderer = renderer; } this.isDestroyingSubtree = false; this._dispatching = null; }, /** If the view is currently inserted into the DOM of a parent view, this property will point to the parent of the view. @property parentView @type Ember.View @default null */ parentView: null, _state: null, instrumentName: "core_view", instrumentDetails: function (hash) { hash.object = this.toString(); hash.containerKey = this._debugContainerKey; hash.view = this; }, /** Override the default event firing from `Ember.Evented` to also call methods with the given name. @method trigger @param name {String} @private */ trigger: function () { this._super.apply(this, arguments); var name = arguments[0]; var method = this[name]; if (method) { var length = arguments.length; var args = new Array(length - 1); for (var i = 1; i < length; i++) { args[i - 1] = arguments[i]; } return method.apply(this, args); } }, has: function (name) { return utils.typeOf(this[name]) === "function" || this._super(name); }, destroy: function () { var parent = this.parentView; if (!this._super.apply(this, arguments)) { return; } this.currentState.cleanup(this); if (!this.ownerView.isDestroyingSubtree) { this.ownerView.isDestroyingSubtree = true; if (parent) { parent.removeChild(this); } if (this._renderNode) { Ember.assert("BUG: Render node exists without concomitant env.", this.ownerView.env); htmlbars_runtime.internal.clearMorph(this._renderNode, this.ownerView.env, true); } this.ownerView.isDestroyingSubtree = false; } return this; }, clearRenderedChildren: K, _transitionTo: K, destroyElement: K }); CoreView.reopenClass({ isViewFactory: true }); var DeprecatedCoreView = CoreView.extend({ init: function () { Ember.deprecate("Ember.CoreView is deprecated. Please use Ember.View.", false); this._super.apply(this, arguments); } }); var _domHelper; function domHelper() { return _domHelper = _domHelper || Ember.__loader.require("ember-htmlbars/system/dom-helper")["default"]; } exports['default'] = CoreView; exports.DeprecatedCoreView = DeprecatedCoreView; }); enifed('ember-views/views/legacy_each_view', ['exports', 'ember-htmlbars/templates/legacy-each', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/computed', 'ember-views/views/view', 'ember-views/views/collection_view', 'ember-views/mixins/empty_view_support'], function (exports, legacyEachTemplate, property_get, property_set, computed, View, collection_view, EmptyViewSupport) { 'use strict'; //2.0TODO: Remove this in 2.0 //This is a fallback path for the `{{#each}}` helper that supports deprecated //behavior such as itemController. exports['default'] = View['default'].extend(EmptyViewSupport['default'], { template: legacyEachTemplate['default'], tagName: "", _arrayController: computed.computed(function () { var itemController = this.getAttr("itemController"); var controller = property_get.get(this, "container").lookupFactory("controller:array").create({ _isVirtual: true, parentController: property_get.get(this, "controller"), itemController: itemController, target: property_get.get(this, "controller"), _eachView: this, content: this.getAttr("content") }); return controller; }), willUpdate: function (attrs) { var itemController = this.getAttrFor(attrs, "itemController"); if (itemController) { var arrayController = property_get.get(this, "_arrayController"); property_set.set(arrayController, "content", this.getAttrFor(attrs, "content")); } }, _arrangedContent: computed.computed("attrs.content", function () { if (this.getAttr("itemController")) { return property_get.get(this, "_arrayController"); } return this.getAttr("content"); }), _itemTagName: computed.computed(function () { var tagName = property_get.get(this, "tagName"); return collection_view.CONTAINER_MAP[tagName]; }) }); }); enifed('ember-views/views/select', ['exports', 'ember-metal/enumerable_utils', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-views/views/view', 'ember-runtime/utils', 'ember-metal/is_none', 'ember-metal/computed', 'ember-runtime/system/native_array', 'ember-metal/mixin', 'ember-metal/properties', 'ember-htmlbars/templates/select', 'ember-htmlbars/templates/select-option', 'ember-htmlbars/templates/select-optgroup'], function (exports, enumerable_utils, property_get, property_set, View, utils, isNone, computed, native_array, mixin, properties, htmlbarsTemplate, selectOptionDefaultTemplate, selectOptgroupDefaultTemplate) { 'use strict'; /** @module ember @submodule ember-views */ var defaultTemplate = htmlbarsTemplate['default']; var SelectOption = View['default'].extend({ instrumentDisplay: "Ember.SelectOption", tagName: "option", attributeBindings: ["value", "selected"], defaultTemplate: selectOptionDefaultTemplate['default'], content: null, willRender: function () { this.labelPathDidChange(); this.valuePathDidChange(); }, selected: computed.computed(function () { var value = property_get.get(this, "value"); var selection = property_get.get(this, "attrs.selection"); if (property_get.get(this, "attrs.multiple")) { return selection && enumerable_utils.indexOf(selection, value) > -1; } else { // Primitives get passed through bindings as objects... since // `new Number(4) !== 4`, we use `==` below return value == property_get.get(this, "attrs.parentValue"); // jshint ignore:line } }).property("attrs.content", "attrs.selection"), labelPathDidChange: mixin.observer("attrs.optionLabelPath", function () { var labelPath = property_get.get(this, "attrs.optionLabelPath"); properties.defineProperty(this, "label", computed.computed.alias(labelPath)); }), valuePathDidChange: mixin.observer("attrs.optionValuePath", function () { var valuePath = property_get.get(this, "attrs.optionValuePath"); properties.defineProperty(this, "value", computed.computed.alias(valuePath)); }) }); var SelectOptgroup = View['default'].extend({ instrumentDisplay: "Ember.SelectOptgroup", tagName: "optgroup", defaultTemplate: selectOptgroupDefaultTemplate['default'], attributeBindings: ["label"] }); /** The `Ember.Select` view class renders a [select](https://developer.mozilla.org/en/HTML/Element/select) HTML element, allowing the user to choose from a list of options. The text and `value` property of each ` ``` The `value` attribute of the selected `