/*! * @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.4 */ (function() { var enifed, requireModule, eriuqer, requirejs, Ember; var mainContext = this; (function() { var isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; if (!isNode) { 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 2) { args = new Array(length - 2); for (var i = 0, l = length - 2; i < l; i++) { args[i] = arguments[i + 2]; } } else { args = []; } var onError = getOnError(this.options); this.begin(); // guard against Safari 6's double-finally bug var didFinally = false; if (onError) { try { return method.apply(target, args); } catch (error) { onError(error); } finally { if (!didFinally) { didFinally = true; this.end(); } } } else { try { return method.apply(target, args); } finally { if (!didFinally) { didFinally = true; this.end(); } } } }, join: function () { if (this.currentInstance) { var length = arguments.length; var method, target; if (length === 1) { method = arguments[0]; target = null; } else { target = arguments[0]; method = arguments[1]; } if (_backburnerUtils.isString(method)) { method = target[method]; } if (length === 1) { return method(); } else if (length === 2) { return method.call(target); } else { var args = new Array(length - 2); for (var i = 0, l = length - 2; i < l; i++) { args[i] = arguments[i + 2]; } return method.apply(target, args); } } else { return this.run.apply(this, arguments); } }, defer: function (queueName /* , target, method, args */) { var length = arguments.length; var method, target, args; if (length === 2) { method = arguments[1]; target = null; } else { target = arguments[1]; method = arguments[2]; } if (_backburnerUtils.isString(method)) { method = target[method]; } var stack = this.DEBUG ? new Error() : undefined; 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, false, stack); }, deferOnce: function (queueName /* , target, method, args */) { var length = arguments.length; var method, target, args; if (length === 2) { method = arguments[1]; target = null; } else { target = arguments[1]; method = arguments[2]; } if (_backburnerUtils.isString(method)) { method = target[method]; } var stack = this.DEBUG ? new Error() : undefined; 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 (_backburnerUtils.isFunction(methodOrWait) || _backburnerUtils.isFunction(methodOrTarget[methodOrWait])) { target = args.shift(); method = args.shift(); wait = 0; } else if (_backburnerUtils.isCoercableNumber(methodOrWait)) { method = args.shift(); wait = args.shift(); } else { method = args.shift(); wait = 0; } } else { var last = args[args.length - 1]; if (_backburnerUtils.isCoercableNumber(last)) { wait = args.pop(); } else { wait = 0; } methodOrTarget = args[0]; methodOrArgs = args[1]; if (_backburnerUtils.isFunction(methodOrArgs) || _backburnerUtils.isString(methodOrArgs) && methodOrTarget !== null && methodOrArgs in methodOrTarget) { target = args.shift(); method = args.shift(); } else { method = args.shift(); } } var executeAt = _backburnerUtils.now() + parseInt(wait, 10); if (_backburnerUtils.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 = _backburnerBinarySearch["default"](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 = new Array(arguments.length); for (var i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } var immediate = args.pop(); var wait, throttler, index, timer; if (_backburnerUtils.isNumber(immediate) || _backburnerUtils.isString(immediate)) { wait = immediate; immediate = true; } else { wait = args.pop(); } wait = parseInt(wait, 10); index = findThrottler(target, method, this._throttlers); if (index > -1) { return this._throttlers[index]; } // throttled timer = _backburnerPlatform["default"].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 = new Array(arguments.length); for (var i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } var immediate = args.pop(); var wait, index, debouncee, timer; if (_backburnerUtils.isNumber(immediate) || _backburnerUtils.isString(immediate)) { wait = immediate; immediate = false; } else { wait = args.pop(); } 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 = _backburnerPlatform["default"].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]); }; _backburnerUtils.each(this._throttlers, clearItems); this._throttlers = []; _backburnerUtils.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] - _backburnerUtils.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 (_backburnerPlatform.needsIETryCatchFix) { var originalRun = Backburner.prototype.run; Backburner.prototype.run = _backburnerUtils.wrapInTryCatch(originalRun); var originalEnd = Backburner.prototype.end; Backburner.prototype.end = _backburnerUtils.wrapInTryCatch(originalEnd); } function getOnError(options) { return options.onError || options.onErrorTarget && options.onErrorTarget[options.onErrorMethod]; } function createAutorun(backburner) { backburner.begin(); backburner._autorun = _backburnerPlatform["default"].setTimeout(function () { backburner._autorun = null; backburner.end(); }); } function updateLaterTimer(backburner, executeAt, wait) { var n = _backburnerUtils.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 = _backburnerPlatform["default"].setTimeout(function () { backburner._laterTimer = null; backburner._laterTimerExpiresAt = null; executeTimers(backburner); }, wait); backburner._laterTimerExpiresAt = n + wait; } } function executeTimers(backburner) { var n = _backburnerUtils.now(); var fns, i, l; backburner.run(function () { i = _backburnerBinarySearch["default"](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; } }); /* target, method, args */ /* target, method, args */ enifed("backburner/binary-search", ["exports"], function (exports) { exports["default"] = binarySearch; 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', ['exports', './utils', './queue'], function (exports, _utils, _queue) { exports["default"] = DeferredActionQueues; function DeferredActionQueues(queueNames, options) { var queues = this.queues = {}; this.queueNames = queueNames = queueNames || []; this.options = options; _utils.each(queueNames, function (queueName) { queues[queueName] = new _queue["default"](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; } } } }; }); enifed('backburner/platform', ['exports'], function (exports) { // 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; var platform; /* global self */ if (typeof self === 'object') { platform = self; /* global global */ } else if (typeof global === 'object') { platform = global; } else { throw new Error('no global: `self` or `global` found'); } exports["default"] = platform; }); enifed('backburner/queue', ['exports', './utils'], function (exports, _utils) { exports["default"] = Queue; function Queue(name, options, globalOptions) { this.name = name; this.globalOptions = globalOptions || {}; this.options = options; this._queue = []; this.targetQueues = {}; 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 += 2) { 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 (_utils.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; } } } }; }); enifed('backburner/utils', ['exports'], function (exports) { exports.each = each; exports.isString = isString; exports.isFunction = isFunction; exports.isNumber = isNumber; exports.isCoercableNumber = isCoercableNumber; exports.wrapInTryCatch = wrapInTryCatch; var NUMBER = /\d+/; function each(collection, callback) { for (var i = 0; i < collection.length; i++) { callback(collection[i]); } } // 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'; } function isFunction(suspect) { return typeof suspect === 'function'; } function isNumber(suspect) { return typeof suspect === 'number'; } function isCoercableNumber(number) { return isNumber(number) || NUMBER.test(number); } function wrapInTryCatch(func) { return function () { try { return func.apply(this, arguments); } catch (e) { throw e; } }; } }); enifed('calculateVersion', ['exports'], function (exports) { '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, _containerRegistry, _containerContainer) { /* Public api for the container is still in flux. The public api, specified on the application namespace should be considered the stable api. // @module container @private */ /* Flag to enable/disable model factory injections (disabled by default) If model factory injections are enabled, models should not be accessed globally (only through `container.lookupFactory('model:modelName'))`); */ 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 = _containerRegistry["default"]; exports.Container = _containerContainer["default"]; }); enifed('container/container', ['exports', 'ember-metal/core', 'ember-metal/keys', 'ember-metal/dictionary'], function (exports, _emberMetalCore, _emberMetalKeys, _emberMetalDictionary) { // TODO - Temporary workaround for v0.4.0 of the ES6 transpiler, which lacks support for circular dependencies. // See the below usage of requireModule. Instead, it should be possible to simply `import Registry from './registry';` 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 () { _emberMetalCore["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 = _emberMetalDictionary["default"](options && options.cache ? options.cache : null); this.factoryCache = _emberMetalDictionary["default"](options && options.factoryCache ? options.factoryCache : null); this.validationCache = _emberMetalDictionary["default"](options && options.validationCache ? options.validationCache : null); } Container.prototype = { /** @private @property _registry @type Registry @since 1.11.0 */ _registry: null, /** @private @property cache @type InheritingDict */ cache: null, /** @private @property factoryCache @type InheritingDict */ factoryCache: null, /** @private @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 ``` @private @method lookup @param {String} fullName @param {Object} options @return {any} */ lookup: function (fullName, options) { _emberMetalCore["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. @private @method lookupFactory @param {String} fullName @return {any} */ lookupFactory: function (fullName) { _emberMetalCore["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. @private @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. @private @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 () { _emberMetalCore["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' || !_emberMetalCore["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 = _emberMetalKeys["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 = _emberMetalDictionary["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; }); // Ember.assert enifed('container/registry', ['exports', 'ember-metal/core', 'ember-metal/dictionary', 'ember-metal/keys', 'ember-metal/merge', './container'], function (exports, _emberMetalCore, _emberMetalDictionary, _emberMetalKeys, _emberMetalMerge, _container) { var VALID_FULL_NAME_REGEXP = /^[^:]+.+:[^:]+$/; var instanceInitializersFeatureEnabled; if (_emberMetalCore["default"].FEATURES.isEnabled('ember-application-instance-initializers')) { 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 = _emberMetalDictionary["default"](options && options.registrations ? options.registrations : null); this._typeInjections = _emberMetalDictionary["default"](null); this._injections = _emberMetalDictionary["default"](null); this._factoryTypeInjections = _emberMetalDictionary["default"](null); this._factoryInjections = _emberMetalDictionary["default"](null); this._normalizeCache = _emberMetalDictionary["default"](null); this._resolveCache = _emberMetalDictionary["default"](null); this._failCache = _emberMetalDictionary["default"](null); this._options = _emberMetalDictionary["default"](null); this._typeOptions = _emberMetalDictionary["default"](null); } Registry.prototype = { /** A backup registry for resolving registrations when no matches can be found. @private @property fallback @type Registry */ fallback: null, /** @private @property resolver @type function */ resolver: null, /** @private @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. @private @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. @private @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) { _emberMetalCore["default"].assert('Create a container on the registry (with `registry.container()`) before calling `lookup`.', this._defaultContainer); if (instanceInitializersFeatureEnabled) { _emberMetalCore["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) { _emberMetalCore["default"].assert('Create a container on the registry (with `registry.container()`) before calling `lookupFactory`.', this._defaultContainer); if (instanceInitializersFeatureEnabled) { _emberMetalCore["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}); ``` @private @method register @param {String} fullName @param {Function} factory @param {Object} options */ register: function (fullName, factory, options) { _emberMetalCore["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 ``` @private @method unregister @param {String} fullName */ unregister: function (fullName) { _emberMetalCore["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 ``` @private @method resolve @param {String} fullName @return {Function} fullName's factory */ resolve: function (fullName) { _emberMetalCore["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`. @private @method describe @param {String} fullName @return {string} described fullName */ describe: function (fullName) { return fullName; }, /** A hook to enable custom fullName normalization behaviour @private @method normalizeFullName @param {String} fullName @return {string} normalized fullName */ normalizeFullName: function (fullName) { return fullName; }, /** normalize a fullName based on the applications conventions @private @method normalize @param {String} fullName @return {string} normalized fullName */ normalize: function (fullName) { return this._normalizeCache[fullName] || (this._normalizeCache[fullName] = this.normalizeFullName(fullName)); }, /** @method makeToString @private @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. @private @method has @param {String} fullName @return {Boolean} */ has: function (fullName) { _emberMetalCore["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 ``` @private @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; }, /** @private @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) { _emberMetalCore["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) { _emberMetalCore["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 ``` @private @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); } _emberMetalCore["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 ``` @private @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 }); }, /** @method knownForType @param {String} type the type to iterate over @private */ knownForType: function (type) { var fallbackKnown = undefined, resolverKnown = undefined; var localKnown = _emberMetalDictionary["default"](null); var registeredNames = _emberMetalKeys["default"](this.registrations); for (var index = 0, _length = registeredNames.length; index < _length; index++) { var fullName = registeredNames[index]; var itemType = fullName.split(':')[0]; if (itemType === type) { localKnown[fullName] = true; } } if (this.fallback) { fallbackKnown = this.fallback.knownForType(type); } if (this.resolver.knownForType) { resolverKnown = this.resolver.knownForType(type); } return _emberMetalMerge.assign({}, fallbackKnown, localKnown, resolverKnown); }, 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)) { _emberMetalCore["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; }); // Ember.assert enifed("dag-map", ["exports"], function (exports) { 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', ['exports', './dag-map'], function (exports, _dagMap) { /* global define:true module:true window: true */ if (typeof enifed === 'function' && enifed.amd) { enifed(function () { return _dagMap["default"]; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports = _dagMap["default"]; } else if (typeof this !== 'undefined') { this['DAG'] = _dagMap["default"]; } }); enifed("dom-helper", ["exports", "./htmlbars-runtime/morph", "./morph-attr", "./dom-helper/build-html-dom", "./dom-helper/classes", "./dom-helper/prop"], function (exports, _htmlbarsRuntimeMorph, _morphAttr, _domHelperBuildHtmlDom, _domHelperClasses, _domHelperProp) { 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(_domHelperBuildHtmlDom.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 === _domHelperBuildHtmlDom.svgNamespace && !_domHelperBuildHtmlDom.svgHTMLIntegrationPoints[element.tagName]) { return _domHelperBuildHtmlDom.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 === _domHelperBuildHtmlDom.svgNamespace || lowercaseName === "style") { if (_domHelperProp.isAttrRemovalValue(value)) { element.removeAttribute(name); } else { if (namespace) { element.setAttributeNS(namespace, name, value); } else { element.setAttribute(name, value); } } } else { var _normalizeProperty = _domHelperProp.normalizeProperty(element, name); var normalized = _normalizeProperty.normalized; var type = _normalizeProperty.type; if (type === "prop") { element[normalized] = value; } else { if (_domHelperProp.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 = _domHelperBuildHtmlDom.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 = _domHelperClasses.addClasses; prototype.removeClasses = _domHelperClasses.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 = _morphAttr["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 = _htmlbarsRuntimeMorph["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 _htmlbarsRuntimeMorph["default"].create(this, contextualElement, fragment); }; prototype.replaceContentWithMorph = function (element) { var firstChild = element.firstChild; if (!firstChild) { var comment = this.createComment(""); this.appendChild(element, comment); return _htmlbarsRuntimeMorph["default"].create(this, element, comment); } else { var morph = _htmlbarsRuntimeMorph["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.setMorphHTML = function (morph, html) { morph.setHTML(html); }; prototype.parseHTML = function (html, contextualElement) { var childNodes; if (interiorNamespace(contextualElement) === _domHelperBuildHtmlDom.svgNamespace) { childNodes = buildSVGDOM(html, this); } else { var nodes = _domHelperBuildHtmlDom.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) { exports.buildHTMLDOM = buildHTMLDOM = function buildHTMLDOM(html, contextualElement, dom) { if (svgHTMLIntegrationPoints[contextualElement.tagName]) { return buildIESafeDOM(html, document.createElement('div'), dom); } else { return buildIESafeDOM(html, contextualElement, dom); } }; } else { exports.buildHTMLDOM = buildHTMLDOM = buildIESafeDOM; } exports.buildHTMLDOM = buildHTMLDOM; }); enifed('dom-helper/classes', ['exports'], function (exports) { 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) { exports.addClasses = 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); } }; exports.removeClasses = 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 { exports.addClasses = addClasses = addClassesViaAttribute; exports.removeClasses = removeClasses = removeClassesViaAttribute; } exports.addClasses = addClasses; exports.removeClasses = removeClasses; }); enifed('dom-helper/prop', ['exports'], function (exports) { exports.isAttrRemovalValue = isAttrRemovalValue; exports.normalizeProperty = normalizeProperty; function isAttrRemovalValue(value) { return value === null || value === undefined; } /* * * @method normalizeProperty * @param element {HTMLElement} * @param slotName {String} * @returns {Object} { name, type } */ function normalizeProperty(element, slotName) { var type, normalized; if (slotName in element) { normalized = slotName; type = 'prop'; } else { var lower = slotName.toLowerCase(); if (lower in element) { type = 'prop'; normalized = lower; } else { type = 'attr'; normalized = slotName; } } if (type === 'prop' && preferAttr(element.tagName, normalized)) { type = 'attr'; } return { normalized: normalized, type: type }; } // properties that MUST be set as attributes, due to: // * browser bug // * strange spec outlier var ATTR_OVERRIDES = { // phantomjs < 2.0 lets you set it as a prop but won't reflect it // back to the attribute. button.getAttribute('type') === null BUTTON: { type: true, form: true }, INPUT: { // TODO: remove when IE8 is droped // Some versions of IE (IE8) throw an exception when setting // `input.list = 'somestring'`: // https://github.com/emberjs/ember.js/issues/10908 // https://github.com/emberjs/ember.js/issues/11364 list: true, // Some version of IE (like IE9) actually throw an exception // if you set input.type = 'something-unknown' type: true, form: true }, // element.form is actually a legitimate readOnly property, that is to be // mutated, but must be mutated by setAttribute... SELECT: { form: true }, OPTION: { form: true }, TEXTAREA: { form: true }, LABEL: { form: true }, FIELDSET: { form: true }, LEGEND: { form: true }, OBJECT: { form: true } }; function preferAttr(tagName, propName) { var tag = ATTR_OVERRIDES[tagName.toUpperCase()]; return tag && tag[propName.toLowerCase()] || false; } }); enifed('ember-application', ['exports', 'ember-metal/core', 'ember-runtime/system/lazy_load', 'ember-application/system/resolver', 'ember-application/system/application', 'ember-application/ext/controller'], function (exports, _emberMetalCore, _emberRuntimeSystemLazy_load, _emberApplicationSystemResolver, _emberApplicationSystemApplication, _emberApplicationExtController) { // side effect of extending ControllerMixin _emberMetalCore["default"].Application = _emberApplicationSystemApplication["default"]; _emberMetalCore["default"].Resolver = _emberApplicationSystemResolver.Resolver; _emberMetalCore["default"].DefaultResolver = _emberApplicationSystemResolver["default"]; _emberRuntimeSystemLazy_load.runLoadHooks('Ember.Application', _emberApplicationSystemApplication["default"]); }); /** @module ember @submodule ember-application */ 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, _emberMetalCore, _emberMetalProperty_get, _emberMetalError, _emberMetalUtils, _emberMetalComputed, _emberRuntimeMixinsController, _emberRoutingSystemController_for) { function verifyNeedsDependencies(controller, container, needs) { var dependency, i, l; var missing = []; for (i = 0, l = needs.length; i < l; i++) { dependency = needs[i]; _emberMetalCore["default"].assert(_emberMetalUtils.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 _emberMetalError["default"](_emberMetalUtils.inspect(controller) + " needs [ " + missing.join(", ") + " ] but " + (missing.length > 1 ? "they" : "it") + " could not be found"); } } var defaultControllersComputedProperty = _emberMetalComputed.computed(function () { var controller = this; return { needs: _emberMetalProperty_get.get(controller, "needs"), container: _emberMetalProperty_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 = _emberMetalUtils.inspect(controller) + "#needs does not include `" + controllerName + "`. To access the " + controllerName + " controller from " + _emberMetalUtils.inspect(controller) + ", " + _emberMetalUtils.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 " + _emberMetalUtils.inspect(controller)); } }; }); /** @class ControllerMixin @namespace Ember @public */ _emberRuntimeMixinsController["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. @deprecated Use `Ember.inject.controller()` instead. @property {Array} needs @default [] @public */ needs: [], init: function () { var needs = _emberMetalProperty_get.get(this, "needs"); var length = _emberMetalProperty_get.get(needs, "length"); if (length > 0) { _emberMetalCore["default"].assert(" `" + _emberMetalUtils.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 _emberMetalProperty_get.get(this, "controllers"); } this._super.apply(this, arguments); }, /** @method controllerFor @see {Ember.Route#controllerFor} @deprecated Use `needs` instead @public */ controllerFor: function (controllerName) { _emberMetalCore["default"].deprecate("Controller#controllerFor is deprecated, please use Controller#needs instead"); return _emberRoutingSystemController_for["default"](_emberMetalProperty_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 @public */ controllers: defaultControllersComputedProperty }); exports["default"] = _emberRuntimeMixinsController["default"]; }); /** @module ember @submodule ember-application @public */ // Ember.assert 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, _emberMetalProperty_get, _emberMetalProperty_set, _emberRuntimeSystemObject, _emberMetalRun_loop, _emberMetalComputed, _containerRegistry) { /** The `ApplicationInstance` encapsulates all of the stateful aspects of a running `Application`. At a high-level, we break application boot into two distinct phases: * Definition time, where all of the classes, templates, and other dependencies are loaded (typically in the browser). * Run time, where we begin executing the application once everything has loaded. Definition time can be expensive and only needs to happen once since it is an idempotent operation. For example, between test runs and FastBoot requests, the application stays the same. It is only the state that we want to reset. That state is what the `ApplicationInstance` manages: it is responsible for creating the container that contains all application state, and disposing of it once the particular test run or FastBoot request has finished. @public */ exports["default"] = _emberRuntimeSystemObject["default"].extend({ /** The application instance's container. The container stores all of the instance-specific state for this application run. @property {Ember.Container} container @public */ container: null, /** The application's registry. The registry contains the classes, templates, and other code that makes up the application. @property {Ember.Registry} registry @private */ applicationRegistry: null, /** The registry for this application instance. It should use the `applicationRegistry` as a fallback. @property {Ember.Registry} registry @private */ 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 _containerRegistry["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: _emberMetalComputed.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 = _emberMetalProperty_get.get(this, "router"); if (location) { _emberMetalProperty_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 = _emberMetalProperty_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 = _emberMetalProperty_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 = _emberMetalProperty_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); _emberMetalRun_loop["default"](this.container, "destroy"); } }); }); /** @module ember @submodule ember-application @private */ 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, _dagMap, _containerRegistry, _emberMetal, _emberMetalProperty_get, _emberMetalProperty_set, _emberRuntimeSystemLazy_load, _emberRuntimeSystemNamespace, _emberRuntimeMixinsDeferred, _emberApplicationSystemResolver, _emberMetalPlatformCreate, _emberMetalRun_loop, _emberMetalUtils, _emberRuntimeControllersController, _emberMetalEnumerable_utils, _emberRuntimeControllersObject_controller, _emberRuntimeControllersArray_controller, _emberMetalViewsRenderer, _emberHtmlbarsSystemDomHelper, _emberViewsViewsSelect, _emberRoutingViewsViewsOutlet, _emberViewsViewsView, _emberViewsSystemEvent_dispatcher, _emberViewsSystemJquery, _emberRoutingSystemRoute, _emberRoutingSystemRouter, _emberRoutingLocationHash_location, _emberRoutingLocationHistory_location, _emberRoutingLocationAuto_location, _emberRoutingLocationNone_location, _emberRoutingSystemCache, _emberApplicationSystemApplicationInstance, _emberViewsViewsText_field, _emberViewsViewsText_area, _emberViewsViewsCheckbox, _emberViewsViewsLegacy_each_view, _emberRoutingViewsViewsLink, _emberRoutingServicesRouting, _emberExtensionSupportContainer_debug_adapter, _emberMetalEnvironment) { 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 @public */ var Application = _emberRuntimeSystemNamespace["default"].extend(_emberRuntimeMixinsDeferred["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' @public */ 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 @public */ 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 @public */ 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.$ = _emberViewsSystemJquery["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; if (_emberMetal["default"].FEATURES.isEnabled('ember-application-visit')) { if (this.autoboot) { // Create subclass of Ember.Router for this Application instance. // This is to ensure that someone reopening `App.Router` does not // tamper with the default `Ember.Router`. // 2.0TODO: Can we move this into a globals-mode-only library? this.Router = (this.Router || _emberRoutingSystemRouter["default"]).extend(); this.buildDefaultInstance(); this.waitForDOMReady(); } } else { this.Router = (this.Router || _emberRoutingSystemRouter["default"]).extend(); this.buildDefaultInstance(); this.waitForDOMReady(); } }, /** 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 _emberApplicationSystemApplicationInstance["default"].create({ customEvents: _emberMetalProperty_get.get(this, 'customEvents'), rootElement: _emberMetalProperty_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. _emberViewsViewsView["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 waitForDOMReady */ waitForDOMReady: function () { if (!this.$ || this.$.isReady) { _emberMetalRun_loop["default"].schedule('actions', this, 'domReady'); } else { this.$().ready(_emberMetalRun_loop["default"].bind(this, 'domReady')); } }, /** 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 @public */ deferReadiness: function () { _emberMetal["default"].assert('You must call deferReadiness on an instance of Ember.Application', this instanceof Application); _emberMetal["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} @public */ advanceReadiness: function () { _emberMetal["default"].assert('You must call advanceReadiness on an instance of Ember.Application', this instanceof Application); this._readinessDeferrals--; if (this._readinessDeferrals === 0) { _emberMetalRun_loop["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 @public **/ 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} @public **/ 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 () { _emberMetal["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 domReady */ domReady: function () { if (this.isDestroyed) { return; } this.boot(); return this; }, boot: function () { if (this._bootPromise) { return this._bootPromise; } var defer = new _emberMetal["default"].RSVP.defer(); this._bootPromise = defer.promise; this._bootResolver = defer; this.runInitializers(this.registry); _emberRuntimeSystemLazy_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 @public **/ reset: function () { var instance = this.__deprecatedInstance__; this._readinessDeferrals = 1; this._bootPromise = null; this._bootResolver = null; function handleReset() { _emberMetalRun_loop["default"](instance, 'destroy'); _emberMetalRun_loop["default"].schedule('actions', this, 'domReady', this.buildDefaultInstance()); } _emberMetalRun_loop["default"].join(this, handleReset); }, /** @private @method runInitializers */ runInitializers: function (registry) { var App = this; this._runInitializer('initializers', function (name, initializer) { _emberMetal["default"].assert('No application initializer named \'' + name + '\'', !!initializer); if (_emberMetal["default"].FEATURES.isEnabled('ember-application-initializer-context')) { initializer.initialize(registry, App); } else { var ref = initializer.initialize; ref(registry, App); } }); }, runInstanceInitializers: function (instance) { this._runInitializer('instanceInitializers', function (name, initializer) { _emberMetal["default"].assert('No instance initializer named \'' + name + '\'', !!initializer); initializer.initialize(instance); }); }, _runInitializer: function (bucketName, cb) { var initializersByName = _emberMetalProperty_get.get(this.constructor, bucketName); var initializers = props(initializersByName); var graph = new _dagMap["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 (_emberMetalEnvironment["default"].hasDOM) { this.__deprecatedInstance__.setupEventDispatcher(); } this.runInstanceInitializers(this.__deprecatedInstance__); this.ready(); // user hook this.__deprecatedInstance__.startRouting(); if (!_emberMetal["default"].testing) { // Eagerly name all classes that are already loaded _emberMetal["default"].Namespace.processAll(); _emberMetal["default"].BOOTED = true; } this.resolve(this); } this._bootResolver.resolve(); }, /** Called when the Application has become ready, immediately before routing begins. The call will be delayed until the DOM has become ready. @event ready @public */ ready: function () { return this; }, /** Set this to provide an alternate class to `Ember.DefaultResolver` @deprecated Use 'Resolver' instead @property resolver @public */ resolver: null, /** Set this to provide an alternate class to `Ember.DefaultResolver` @property resolver @public */ Resolver: null, // This method must be moved to the application instance object willDestroy: function () { this._super.apply(this, arguments); _emberMetal["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 () { _emberMetal["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); } }); if (_emberMetal["default"].FEATURES.isEnabled('ember-application-instance-initializers')) { Application.reopen({ instanceInitializer: function (options) { this.constructor.instanceInitializer(options); } }); Application.reopenClass({ instanceInitializer: buildInitializerMethod('instanceInitializers', 'instance initializer') }); } if (_emberMetal["default"].FEATURES.isEnabled('ember-application-visit')) { Application.reopen({ /** Creates a new instance of the application and instructs it to route to the specified initial URL. This method returns a promise that will be resolved once rendering is complete. That promise is resolved with the instance. ```js App.visit('/users').then(function(instance) { var view = instance.view; view.appendTo('#qunit-test-fixtures'); }); ``` @method visit @private */ visit: function (url) { var instance = this.buildInstance(); this.runInstanceInitializers(instance); var renderPromise = new _emberMetal["default"].RSVP.Promise(function (res, rej) { instance.didCreateRootView = function (view) { instance.view = view; res(instance); }; }); instance.overrideRouterLocation({ location: 'none' }); return instance.handleURL(url).then(function () { return renderPromise; }); } }); } Application.reopenClass({ initializers: _emberMetalPlatformCreate["default"](null), instanceInitializers: _emberMetalPlatformCreate["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} @public */ 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 @public */ buildRegistry: function (namespace) { var registry = new _containerRegistry["default"](); registry.set = _emberMetalProperty_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.register('application:main', namespace, { instantiate: false }); registry.register('controller:basic', _emberRuntimeControllersController["default"], { instantiate: false }); registry.register('controller:object', _emberRuntimeControllersObject_controller["default"], { instantiate: false }); registry.register('controller:array', _emberRuntimeControllersArray_controller["default"], { instantiate: false }); registry.register('renderer:-dom', { create: function () { return new _emberMetalViewsRenderer["default"](new _emberHtmlbarsSystemDomHelper["default"]()); } }); registry.injection('view', 'renderer', 'renderer:-dom'); registry.register('view:select', _emberViewsViewsSelect["default"]); registry.register('view:-outlet', _emberRoutingViewsViewsOutlet.OutletView); registry.register('-view-registry:main', { create: function () { return {}; } }); registry.injection('view', '_viewRegistry', '-view-registry:main'); registry.register('view:toplevel', _emberViewsViewsView["default"].extend()); registry.register('route:basic', _emberRoutingSystemRoute["default"], { instantiate: false }); registry.register('event_dispatcher:main', _emberViewsSystemEvent_dispatcher["default"]); registry.injection('router:main', 'namespace', 'application:main'); registry.injection('view:-outlet', 'namespace', 'application:main'); registry.register('location:auto', _emberRoutingLocationAuto_location["default"]); registry.register('location:hash', _emberRoutingLocationHash_location["default"]); registry.register('location:history', _emberRoutingLocationHistory_location["default"]); registry.register('location:none', _emberRoutingLocationNone_location["default"]); registry.injection('controller', 'target', 'router:main'); registry.injection('controller', 'namespace', 'application:main'); registry.register('-bucket-cache:main', _emberRoutingSystemCache["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', _emberViewsViewsText_field["default"]); registry.register('component:-text-area', _emberViewsViewsText_area["default"]); registry.register('component:-checkbox', _emberViewsViewsCheckbox["default"]); registry.register('view:-legacy-each', _emberViewsViewsLegacy_each_view["default"]); registry.register('component:-link-to', _emberRoutingViewsViewsLink["default"]); // Register the routing service... registry.register('service:-routing', _emberRoutingServicesRouting["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', _emberExtensionSupportContainer_debug_adapter["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) { _emberMetal["default"].deprecate('Application.resolver is deprecated in favor of Application.Resolver', !namespace.get('resolver')); var ResolverClass = namespace.get('resolver') || namespace.get('Resolver') || _emberApplicationSystemResolver["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 { _emberMetal["default"].deprecate('The Resolver should now provide a \'normalize\' function', false); return fullName; } }; resolve.knownForType = function knownForType(type) { if (resolver.knownForType) { return resolver.knownForType(type); } }; resolve.moduleBasedResolver = resolver.moduleBasedResolver; resolve.__resolver__ = resolver; return resolve; } function registerLibraries() { if (!librariesRegistered) { librariesRegistered = true; if (_emberMetalEnvironment["default"].hasDOM) { _emberMetal["default"].libraries.registerCoreLibrary('jQuery', _emberViewsSystemJquery["default"]().jquery); } } } function logLibraryVersions() { if (_emberMetal["default"].LOG_VERSION) { // we only need to see this once per Application#init _emberMetal["default"].LOG_VERSION = false; var libs = _emberMetal["default"].libraries._registry; var nameLengths = _emberMetalEnumerable_utils.map(libs, function (item) { return _emberMetalProperty_get.get(item, 'name.length'); }); var maxNameLength = Math.max.apply(this, nameLengths); _emberMetal["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(' '); _emberMetal["default"].debug([lib.name, spaces, ' : ', lib.version].join('')); } _emberMetal["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] = _emberMetalPlatformCreate["default"](this[bucketName]); this.reopenClass(attrs); } _emberMetal["default"].assert('The ' + humanName + ' \'' + initializer.name + '\' has already been registered', !this[bucketName][initializer.name]); _emberMetal["default"].assert('An ' + humanName + ' cannot be registered without an initialize function', _emberMetalUtils.canInvoke(initializer, 'initialize')); _emberMetal["default"].assert('An ' + humanName + ' cannot be registered without a name property', initializer.name !== undefined); this[bucketName][initializer.name] = initializer; }; } exports["default"] = Application; }); /** @module ember @submodule ember-application */ // Ember.FEATURES, Ember.deprecate, Ember.assert, Ember.libraries, LOG_VERSION, Namespace, BOOTED enifed('ember-application/system/resolver', ['exports', 'ember-metal/core', 'ember-metal/property_get', 'ember-metal/logger', 'ember-metal/keys', '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, _emberMetalCore, _emberMetalProperty_get, _emberMetalLogger, _emberMetalKeys, _emberRuntimeSystemString, _emberRuntimeSystemObject, _emberRuntimeSystemNamespace, _emberHtmlbarsHelpers, _emberApplicationUtilsValidateType, _emberMetalDictionary) { var Resolver = _emberRuntimeSystemObject["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.Resolver = Resolver; /** The DefaultResolver defines the default lookup rules to resolve container lookups before consulting the container for registered items: * templates are looked up on `Ember.TEMPLATES` * other names are looked up on the application after converting the name. For example, `controller:post` looks up `App.PostController` by default. * there are some nuances (see examples below) ### How Resolving Works The container calls this object's `resolve` method with the `fullName` argument. It first parses the fullName into an object using `parseName`. Then it checks for the presence of a type-specific instance method of the form `resolve[Type]` and calls it if it exists. For example if it was resolving 'template:post', it would call the `resolveTemplate` method. Its last resort is to call the `resolveOther` method. The methods of this object are designed to be easy to override in a subclass. For example, you could enhance how a template is resolved like so: ```javascript App = Ember.Application.create({ Resolver: Ember.DefaultResolver.extend({ resolveTemplate: function(parsedName) { var resolvedTemplate = this._super(parsedName); if (resolvedTemplate) { return resolvedTemplate; } return Ember.TEMPLATES['not_found']; } }) }); ``` Some examples of how names are resolved: ``` 'template:post' //=> Ember.TEMPLATES['post'] 'template:posts/byline' //=> Ember.TEMPLATES['posts/byline'] 'template:posts.byline' //=> Ember.TEMPLATES['posts/byline'] 'template:blogPost' //=> Ember.TEMPLATES['blogPost'] // OR // Ember.TEMPLATES['blog_post'] 'controller:post' //=> App.PostController 'controller:posts.index' //=> App.PostsIndexController 'controller:blog/post' //=> Blog.PostController 'controller:basic' //=> Ember.Controller 'route:post' //=> App.PostRoute 'route:posts.index' //=> App.PostsIndexRoute 'route:blog/post' //=> Blog.PostRoute 'route:basic' //=> Ember.Route 'view:post' //=> App.PostView 'view:posts.index' //=> App.PostsIndexView 'view:blog/post' //=> Blog.PostView 'view:basic' //=> Ember.View 'foo:post' //=> App.PostFoo 'model:post' //=> App.Post ``` @class DefaultResolver @namespace Ember @extends Ember.Object @public */ exports["default"] = _emberRuntimeSystemObject["default"].extend({ /** This will be set to the Application instance when it is created. @property namespace @public */ namespace: null, init: function () { this._parseNameCache = _emberMetalDictionary["default"](null); }, normalize: function (fullName) { var _fullName$split = fullName.split(':', 2); var type = _fullName$split[0]; var name = _fullName$split[1]; _emberMetalCore["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 @public */ 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) { _emberApplicationUtilsValidateType["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 @public */ 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 = _emberMetalProperty_get.get(this, 'namespace'); var root = namespace; if (type !== 'template' && name.indexOf('/') !== -1) { var parts = name.split('/'); name = parts[parts.length - 1]; var namespaceName = _emberRuntimeSystemString.capitalize(parts.slice(0, -1).join('.')); root = _emberRuntimeSystemNamespace["default"].byName(namespaceName); _emberMetalCore["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' : _emberRuntimeSystemString.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 @public */ lookupDescription: function (fullName) { var parsedName = this.parseName(fullName); var description; if (parsedName.type === 'template') { return 'template at ' + parsedName.fullNameWithoutType.replace(/\./g, '/'); } description = parsedName.root + '.' + _emberRuntimeSystemString.classify(parsedName.name).replace(/\./g, ''); if (parsedName.type !== 'model') { description += _emberRuntimeSystemString.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 @public */ 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 @public */ resolveTemplate: function (parsedName) { var templateName = parsedName.fullNameWithoutType.replace(/\./g, '/'); if (_emberMetalCore["default"].TEMPLATES[templateName]) { return _emberMetalCore["default"].TEMPLATES[templateName]; } templateName = _emberRuntimeSystemString.decamelize(templateName); if (_emberMetalCore["default"].TEMPLATES[templateName]) { return _emberMetalCore["default"].TEMPLATES[templateName]; } }, /** Lookup the view using `resolveOther` @protected @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveView @public */ 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 @public */ 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 @public */ 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 @public */ resolveModel: function (parsedName) { var className = _emberRuntimeSystemString.classify(parsedName.name); var factory = _emberMetalProperty_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 @public */ resolveHelper: function (parsedName) { return this.resolveOther(parsedName) || _emberHtmlbarsHelpers["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 @public */ resolveOther: function (parsedName) { var className = _emberRuntimeSystemString.classify(parsedName.name) + _emberRuntimeSystemString.classify(parsedName.type); var factory = _emberMetalProperty_get.get(parsedName.root, className); if (factory) { return factory; } }, resolveMain: function (parsedName) { var className = _emberRuntimeSystemString.classify(parsedName.type); return _emberMetalProperty_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('.'); } _emberMetalLogger["default"].info(symbol, parsedName.fullName, padding, this.lookupDescription(parsedName.fullName)); }, /** Used to iterate all items of a given type. @method knownForType @param {String} type the type to search for @private */ knownForType: function (type) { var namespace = _emberMetalProperty_get.get(this, 'namespace'); var suffix = _emberRuntimeSystemString.classify(type); var typeRegexp = new RegExp(suffix + '$'); var known = _emberMetalDictionary["default"](null); var knownKeys = _emberMetalKeys["default"](namespace); for (var index = 0, _length = knownKeys.length; index < _length; index++) { var _name = knownKeys[index]; if (typeRegexp.test(_name)) { var containerName = this.translateToContainerFullname(type, _name); known[containerName] = true; } } return known; }, /** Converts provided name from the backing namespace into a container lookup name. Examples: App.FooBarHelper -> helper:foo-bar App.THelper -> helper:t @method translateToContainerFullname @param {String} type @param {String} name @private */ translateToContainerFullname: function (type, name) { var suffix = _emberRuntimeSystemString.classify(type); var namePrefix = name.slice(0, suffix.length * -1); var dasherizedName = _emberRuntimeSystemString.dasherize(namePrefix); return type + ':' + dasherizedName; } }); }); /** @module ember @submodule ember-application */ // Ember.TEMPLATES, Ember.assert enifed('ember-application/utils/validate-type', ['exports'], function (exports) { exports["default"] = validateType; /** @module ember @submodule ember-application */ var VALIDATED_TYPES = { route: ['assert', 'isRouteFactory', 'Ember.Route'], component: ['deprecate', 'isComponentFactory', 'Ember.Component'], view: ['deprecate', 'isViewFactory', 'Ember.View'], service: ['deprecate', 'isServiceFactory', 'Ember.Service'] }; function validateType(resolvedType, parsedName) { var validationAttributes = VALIDATED_TYPES[parsedName.type]; if (!validationAttributes) { return; } var action = validationAttributes[0]; var factoryFlag = validationAttributes[1]; var expectedType = validationAttributes[2]; if (action === 'deprecate') { Ember.deprecate('In Ember 2.0 ' + parsedName.type + ' factories must have an `' + factoryFlag + '` ' + ('property set to true. You registered ' + resolvedType + ' as a ' + parsedName.type + ' ') + ('factory. Either add the `' + factoryFlag + '` property to this factory or ') + ('extend from ' + expectedType + '.'), resolvedType[factoryFlag]); } else { 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-debug/deprecation-manager", "ember-metal/environment"], function (exports, _emberMetalCore, _emberMetalError, _emberMetalLogger, _emberDebugDeprecationManager, _emberMetalEnvironment) { exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags; /** @module ember @submodule ember-debug */ /** @class Ember @public */ 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. @public */ _emberMetalCore["default"].assert = function (desc, test) { var throwAssertion; if (isPlainFunction(test)) { throwAssertion = !test(); } else { throwAssertion = !test; } if (throwAssertion) { throw new _emberMetalError["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. @public */ _emberMetalCore["default"].warn = function (message, test) { if (!test) { _emberMetalLogger["default"].warn("WARNING: " + message); if ("trace" in _emberMetalLogger["default"]) { _emberMetalLogger["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. @public */ _emberMetalCore["default"].debug = function (message) { _emberMetalLogger["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, and a unique `id` for this deprecation. The `id` can be used by Ember debugging tools to change the behavior (raise, log or silence) for that specific deprecation. The `id` should be namespaced by dots, e.g. "view.helper.select". @public */ _emberMetalCore["default"].deprecate = function (message, test, options) { if (_emberMetalCore["default"].ENV.RAISE_ON_DEPRECATION) { _emberDebugDeprecationManager["default"].setDefaultLevel(_emberDebugDeprecationManager.deprecationLevels.RAISE); } if (_emberDebugDeprecationManager["default"].getLevel(options && options.id) === _emberDebugDeprecationManager.deprecationLevels.SILENCE) { return; } var noDeprecation; if (isPlainFunction(test)) { noDeprecation = test(); } else { noDeprecation = test; } if (noDeprecation) { return; } if (options && options.id) { message = message + (" [deprecation id: " + options.id + "]"); } if (_emberDebugDeprecationManager["default"].getLevel(options && options.id) === _emberDebugDeprecationManager.deprecationLevels.RAISE) { throw new _emberMetalError["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) { _emberMetalCore["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 (_emberMetalCore["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; } _emberMetalLogger["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 {Object} [options] The options object for Ember.deprecate. @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 @private */ _emberMetalCore["default"].deprecateFunc = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args.length === 3) { var _ret = (function () { var message = args[0]; var options = args[1]; var func = args[2]; return { v: function () { _emberMetalCore["default"].deprecate(message, false, options); return func.apply(this, arguments); } }; })(); if (typeof _ret === "object") return _ret.v; } else { var _ret2 = (function () { var message = args[0]; var func = args[1]; return { v: function () { _emberMetalCore["default"].deprecate(message); return func.apply(this, arguments); } }; })(); if (typeof _ret2 === "object") return _ret2.v; } }; /** Run a function meant for debugging. Ember build tools will remove any calls to `Ember.runInDebug()` when doing a production build. ```javascript Ember.runInDebug(() => { Ember.Component.reopen({ didInsertElement() { console.log("I'm happy"); } }); }); ``` @method runInDebug @param {Function} func The function to be executed. @since 1.5.0 @public */ _emberMetalCore["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) { _emberMetalCore["default"].warn("Ember.ENV.ENABLE_ALL_FEATURES is only available in canary builds.", !_emberMetalCore["default"].ENV.ENABLE_ALL_FEATURES); _emberMetalCore["default"].warn("Ember.ENV.ENABLE_OPTIONAL_FEATURES is only available in canary builds.", !_emberMetalCore["default"].ENV.ENABLE_OPTIONAL_FEATURES); for (var key in FEATURES) { if (FEATURES.hasOwnProperty(key) && key !== "isEnabled") { _emberMetalCore["default"].warn("FEATURE[\"" + key + "\"] is set as enabled, but FEATURE flags are only available in canary builds.", !FEATURES[key]); } } } } if (!_emberMetalCore["default"].testing) { // Complain if they're using FEATURE flags in builds other than canary _emberMetalCore["default"].FEATURES["features-stripped-test"] = true; var featuresWereStripped = true; if (_emberMetalCore["default"].FEATURES.isEnabled("features-stripped-test")) { featuresWereStripped = false; } delete _emberMetalCore["default"].FEATURES["features-stripped-test"]; _warnIfUsingStrippedFeatureFlags(_emberMetalCore["default"].ENV.FEATURES, featuresWereStripped); // Inform the developer about the Ember Inspector if not installed. var isFirefox = _emberMetalEnvironment["default"].isFirefox; var isChrome = _emberMetalEnvironment["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/"; } _emberMetalCore["default"].debug("For more advanced debugging, install the Ember Inspector from " + downloadURL); } }, false); } } _emberMetalCore["default"].Debug = { _addDeprecationLevel: function (id, level) { _emberDebugDeprecationManager["default"].setLevel(id, level); }, _deprecationLevels: _emberDebugDeprecationManager.deprecationLevels }; /* 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; exports.runningNonEmberDebugJS = runningNonEmberDebugJS; if (runningNonEmberDebugJS) { _emberMetalCore["default"].warn("Please use `ember.debug.js` instead of `ember.js` for development and debugging."); } }); /*global __fail__*/ enifed('ember-debug/deprecation-manager', ['exports', 'ember-metal/dictionary', 'ember-metal/utils'], function (exports, _emberMetalDictionary, _emberMetalUtils) { var deprecationLevels = { RAISE: _emberMetalUtils.symbol('RAISE'), LOG: _emberMetalUtils.symbol('LOG'), SILENCE: _emberMetalUtils.symbol('SILENCE') }; exports.deprecationLevels = deprecationLevels; exports["default"] = { defaultLevel: deprecationLevels.LOG, individualLevels: _emberMetalDictionary["default"](null), setDefaultLevel: function (level) { this.defaultLevel = level; }, setLevel: function (id, level) { this.individualLevels[id] = level; }, getLevel: function (id) { var level = this.individualLevels[id]; if (!level) { level = this.defaultLevel; } return level; } }; }); enifed("ember-extension-support", ["exports", "ember-metal/core", "ember-extension-support/data_adapter", "ember-extension-support/container_debug_adapter"], function (exports, _emberMetalCore, _emberExtensionSupportData_adapter, _emberExtensionSupportContainer_debug_adapter) { _emberMetalCore["default"].DataAdapter = _emberExtensionSupportData_adapter["default"]; _emberMetalCore["default"].ContainerDebugAdapter = _emberExtensionSupportContainer_debug_adapter["default"]; }); /** @module ember @submodule ember-extension-support */ 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, _emberMetalCore, _emberRuntimeSystemNative_array, _emberRuntimeUtils, _emberRuntimeSystemString, _emberRuntimeSystemNamespace, _emberRuntimeSystemObject) { /** @module ember @submodule ember-extension-support */ /** The `ContainerDebugAdapter` helps the container and resolver interface with tools that debug Ember such as the [Ember Extension](https://github.com/tildeio/ember-extension) for Chrome and Firefox. This class can be extended by a custom resolver implementer to override some of the methods with library-specific code. The methods likely to be overridden are: * `canCatalogEntriesByType` * `catalogEntriesByType` The adapter will need to be registered in the application's container as `container-debug-adapter:main` Example: ```javascript Application.initializer({ name: "containerDebugAdapter", initialize: function(container, application) { application.register('container-debug-adapter:main', require('app/container-debug-adapter')); } }); ``` @class ContainerDebugAdapter @namespace Ember @extends Ember.Object @since 1.5.0 @public */ exports["default"] = _emberRuntimeSystemObject["default"].extend({ /** The container of the application being debugged. This property will be injected on creation. @property container @default null @public */ container: null, /** The resolver instance of the application being debugged. This property will be injected on creation. @property resolver @default null @public */ 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. @public */ 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. @public */ catalogEntriesByType: function (type) { var namespaces = _emberRuntimeSystemNative_array.A(_emberRuntimeSystemNamespace["default"].NAMESPACES); var types = _emberRuntimeSystemNative_array.A(); var typeSuffixRegex = new RegExp(_emberRuntimeSystemString.classify(type) + "$"); namespaces.forEach(function (namespace) { if (namespace !== _emberMetalCore["default"]) { for (var key in namespace) { if (!namespace.hasOwnProperty(key)) { continue; } if (typeSuffixRegex.test(key)) { var klass = namespace[key]; if (_emberRuntimeUtils.typeOf(klass) === "class") { types.push(_emberRuntimeSystemString.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, _emberMetalProperty_get, _emberMetalRun_loop, _emberRuntimeSystemString, _emberRuntimeSystemNamespace, _emberRuntimeSystemObject, _emberRuntimeSystemNative_array, _emberApplicationSystemApplication) { /** @module ember @submodule ember-extension-support */ /** The `DataAdapter` helps a data persistence library interface with tools that debug Ember such as the [Ember Extension](https://github.com/tildeio/ember-extension) for Chrome and Firefox. This class will be extended by a persistence library which will override some of the methods with library-specific code. The methods likely to be overridden are: * `getFilters` * `detect` * `columnsForType` * `getRecords` * `getRecordColumnValues` * `getRecordKeywords` * `getRecordFilterValues` * `getRecordColor` * `observeRecord` The adapter will need to be registered in the application's container as `dataAdapter:main` Example: ```javascript Application.initializer({ name: "data-adapter", initialize: function(container, application) { application.register('data-adapter:main', DS.DataAdapter); } }); ``` @class DataAdapter @namespace Ember @extends EmberObject @public */ exports["default"] = _emberRuntimeSystemObject["default"].extend({ init: function () { this._super.apply(this, arguments); this.releaseMethods = _emberRuntimeSystemNative_array.A(); }, /** The container of the application being debugged. This property will be injected on creation. @property container @default null @since 1.3.0 @public */ container: null, /** The container-debug-adapter which is used to list all models. @property containerDebugAdapter @default undefined @since 1.5.0 @public **/ 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, /** Ember Data > v1.0.0-beta.18 requires string model names to be passed around instead of the actual factories. This is a stamp for the Ember Inspector to differentiate between the versions to be able to support older versions too. @public @property acceptsModelName */ acceptsModelName: true, /** Stores all methods that clear observers. These methods will be called on destruction. @private @property releaseMethods @since 1.3.0 */ releaseMethods: _emberRuntimeSystemNative_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 _emberRuntimeSystemNative_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 = _emberRuntimeSystemNative_array.A(); var typesToSend; typesToSend = modelTypes.map(function (type) { var klass = type.klass; var wrapped = _this.wrapModelType(klass, type.name); releaseMethods.push(_this.observeModelType(type.name, 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 {String} modelName The model name @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 (modelName, recordsAdded, recordsUpdated, recordsRemoved) { var _this2 = this; var releaseMethods = _emberRuntimeSystemNative_array.A(); var klass = this._nameToClass(modelName); var records = this.getRecords(klass, modelName); 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 _emberRuntimeSystemNative_array.A(); }, /** Adds observers to a model type class. @private @method observeModelType @param {String} modelName The model type name @param {Function} typesUpdated Called when a type is modified. @return {Function} The function to call to remove observers */ observeModelType: function (modelName, typesUpdated) { var _this3 = this; var klass = this._nameToClass(modelName); var records = this.getRecords(klass, modelName); var onChange = function () { typesUpdated([_this3.wrapModelType(klass, modelName)]); }; var observer = { didChange: function () { _emberMetalRun_loop["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} klass A model class @param {String} modelName 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 (klass, name) { var records = this.getRecords(klass, name); var typeToSend; typeToSend = { name: name, count: _emberMetalProperty_get.get(records, "length"), columns: this.columnsForType(klass), object: klass }; 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 = _emberRuntimeSystemNative_array.A(types).map(function (name) { return { klass: _this4._nameToClass(name), name: name }; }); types = _emberRuntimeSystemNative_array.A(types).filter(function (type) { return _this4.detect(type.klass); }); return _emberRuntimeSystemNative_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 = _emberRuntimeSystemNative_array.A(_emberRuntimeSystemNamespace["default"].NAMESPACES); var types = _emberRuntimeSystemNative_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 `lookupFactory` on non-models // (especially when `Ember.MODEL_FACTORY_INJECTIONS` is `true`) if (!_this5.detect(namespace[key])) { continue; } var name = _emberRuntimeSystemString.dasherize(key); if (!(namespace instanceof _emberApplicationSystemApplication["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 _emberRuntimeSystemNative_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 _emberRuntimeSystemNative_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", ["exports", "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/helpers/-html-safe", "ember-htmlbars/system/dom-helper", "ember-htmlbars/helper", "ember-htmlbars/system/bootstrap", "ember-htmlbars/compat"], function (exports, _emberMetalCore, _emberTemplateCompiler, _emberHtmlbarsSystemMakeViewHelper, _emberHtmlbarsSystemMake_bound_helper, _emberHtmlbarsHelpers, _emberHtmlbarsHelpersIf_unless, _emberHtmlbarsHelpersWith, _emberHtmlbarsHelpersLoc, _emberHtmlbarsHelpersLog, _emberHtmlbarsHelpersEach, _emberHtmlbarsHelpersBindAttrClass, _emberHtmlbarsHelpersNormalizeClass, _emberHtmlbarsHelpersConcat, _emberHtmlbarsHelpersJoinClasses, _emberHtmlbarsHelpersLegacyEachWithController, _emberHtmlbarsHelpersLegacyEachWithKeyword, _emberHtmlbarsHelpersHtmlSafe, _emberHtmlbarsSystemDomHelper, _emberHtmlbarsHelper, _emberHtmlbarsSystemBootstrap, _emberHtmlbarsCompat) { _emberHtmlbarsHelpers.registerHelper("if", _emberHtmlbarsHelpersIf_unless.ifHelper); _emberHtmlbarsHelpers.registerHelper("unless", _emberHtmlbarsHelpersIf_unless.unlessHelper); _emberHtmlbarsHelpers.registerHelper("with", _emberHtmlbarsHelpersWith["default"]); _emberHtmlbarsHelpers.registerHelper("loc", _emberHtmlbarsHelpersLoc["default"]); _emberHtmlbarsHelpers.registerHelper("log", _emberHtmlbarsHelpersLog["default"]); _emberHtmlbarsHelpers.registerHelper("each", _emberHtmlbarsHelpersEach["default"]); _emberHtmlbarsHelpers.registerHelper("-bind-attr-class", _emberHtmlbarsHelpersBindAttrClass["default"]); _emberHtmlbarsHelpers.registerHelper("-normalize-class", _emberHtmlbarsHelpersNormalizeClass["default"]); _emberHtmlbarsHelpers.registerHelper("concat", _emberHtmlbarsHelpersConcat["default"]); _emberHtmlbarsHelpers.registerHelper("-join-classes", _emberHtmlbarsHelpersJoinClasses["default"]); _emberHtmlbarsHelpers.registerHelper("-legacy-each-with-controller", _emberHtmlbarsHelpersLegacyEachWithController["default"]); _emberHtmlbarsHelpers.registerHelper("-legacy-each-with-keyword", _emberHtmlbarsHelpersLegacyEachWithKeyword["default"]); _emberHtmlbarsHelpers.registerHelper("-html-safe", _emberHtmlbarsHelpersHtmlSafe["default"]); _emberMetalCore["default"].HTMLBars = { _registerHelper: _emberHtmlbarsHelpers.registerHelper, template: _emberTemplateCompiler.template, compile: _emberTemplateCompiler.compile, precompile: _emberTemplateCompiler.precompile, makeViewHelper: _emberHtmlbarsSystemMakeViewHelper["default"], makeBoundHelper: _emberHtmlbarsSystemMake_bound_helper["default"], registerPlugin: _emberTemplateCompiler.registerPlugin, DOMHelper: _emberHtmlbarsSystemDomHelper["default"] }; if (_emberMetalCore["default"].FEATURES.isEnabled("ember-htmlbars-helper")) { _emberHtmlbarsHelper["default"].helper = _emberHtmlbarsHelper.helper; _emberMetalCore["default"].Helper = _emberHtmlbarsHelper["default"]; } }); /**   @module ember @submodule ember-templates @main ember-templates @public */ /** [HTMLBars](https://github.com/tildeio/htmlbars) is a [Handlebars](http://handlebarsjs.com/) compatible templating engine used by Ember.js. The classes and namespaces covered by this documentation attempt to focus on APIs for interacting with HTMLBars itself. For more general guidance on Ember.js templates and helpers, please see the [ember-templates](/api/modules/ember-templates.html) package. @module ember @submodule ember-htmlbars @main ember-htmlbars @public */ // importing adds template bootstrapping // initializer to enable embedded templates // importing ember-htmlbars/compat updates the // Ember.Handlebars global if htmlbars is enabled 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, _emberMetalCore, _emberHtmlbarsHelpers, _emberHtmlbarsCompatHelper, _emberHtmlbarsCompatHandlebarsGet, _emberHtmlbarsCompatMakeBoundHelper, _emberHtmlbarsCompatRegisterBoundHelper, _emberHtmlbarsSystemMakeViewHelper, _emberHtmlbarsUtilsString) { var EmberHandlebars = _emberMetalCore["default"].Handlebars = _emberMetalCore["default"].Handlebars || {}; EmberHandlebars.helpers = _emberHtmlbarsHelpers["default"]; EmberHandlebars.helper = _emberHtmlbarsCompatHelper.handlebarsHelper; EmberHandlebars.registerHelper = _emberHtmlbarsCompatHelper.registerHandlebarsCompatibleHelper; EmberHandlebars.registerBoundHelper = _emberHtmlbarsCompatRegisterBoundHelper["default"]; EmberHandlebars.makeBoundHelper = _emberHtmlbarsCompatMakeBoundHelper["default"]; EmberHandlebars.get = _emberHtmlbarsCompatHandlebarsGet["default"]; EmberHandlebars.makeViewHelper = _emberHtmlbarsSystemMakeViewHelper["default"]; EmberHandlebars.SafeString = _emberHtmlbarsUtilsString.SafeString; EmberHandlebars.Utils = { escapeExpression: _emberHtmlbarsUtilsString.escapeExpression }; exports["default"] = EmberHandlebars; }); enifed('ember-htmlbars/compat/handlebars-get', ['exports'], function (exports) { 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 @public */ 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, _emberHtmlbarsHelpers, _emberViewsViewsView, _emberViewsViewsComponent, _emberHtmlbarsSystemMakeViewHelper, _emberHtmlbarsCompatMakeBoundHelper, _emberMetalStreamsUtils, _emberHtmlbarsKeywords) { exports.registerHandlebarsCompatibleHelper = registerHandlebarsCompatibleHelper; exports.handlebarsHelper = handlebarsHelper; var slice = [].slice; function calculateCompatType(item) { if (_emberMetalStreamsUtils.isStream(item)) { return "ID"; } else { var itemType = typeof item; return itemType.toUpperCase(); } } function pathFor(param) { if (_emberMetalStreamsUtils.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) { _emberHtmlbarsKeywords.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); } _emberHtmlbarsHelpers["default"][name] = helper; } function handlebarsHelper(name, value) { Ember.assert("You tried to register a component named '" + name + "', but component names must include a '-'", !_emberViewsViewsComponent["default"].detect(value) || name.match(/-/)); if (_emberViewsViewsView["default"].detect(value)) { _emberHtmlbarsHelpers["default"][name] = _emberHtmlbarsSystemMakeViewHelper["default"](value); } else { var boundHelperArgs = slice.call(arguments, 1); var boundFn = _emberHtmlbarsCompatMakeBoundHelper["default"].apply(this, boundHelperArgs); _emberHtmlbarsHelpers["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; }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/compat/make-bound-helper", ["exports", "ember-metal/streams/utils"], function (exports, _emberMetalStreamsUtils) { exports["default"] = makeBoundHelper; /** @module ember @submodule ember-htmlbars */ /** A helper function used by `registerBoundHelper`. Takes the provided Handlebars helper function fn and returns it in wrapped bound helper form. The main use case for using this outside of `registerBoundHelper` is for registering helpers on the container: ```js var boundHelperFn = Ember.Handlebars.makeBoundHelper(function(word) { return word.toUpperCase(); }); container.register('helper:my-bound-helper', boundHelperFn); ``` In the above example, if the helper function hadn't been wrapped in `makeBoundHelper`, the registered helper would be unbound. @method makeBoundHelper @for Ember.Handlebars @param {Function} fn @param {String} dependentKeys* @since 1.2.0 @deprecated @private */ 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 = _emberMetalStreamsUtils.readArray(params); var properties = new Array(params.length); for (var i = 0, l = params.length; i < l; i++) { var param = params[i]; if (_emberMetalStreamsUtils.isStream(param)) { properties[i] = param.label; } else { properties[i] = param; } } args.push({ hash: _emberMetalStreamsUtils.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, _emberHtmlbarsHelpers, _emberHtmlbarsCompatMakeBoundHelper) { exports["default"] = registerBoundHelper; 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} fn @param {String} dependentKeys* @private */ function registerBoundHelper(name, fn) { var boundHelperArgs = slice.call(arguments, 1); var boundFn = _emberHtmlbarsCompatMakeBoundHelper["default"].apply(this, boundHelperArgs); _emberHtmlbarsHelpers["default"][name] = boundFn; } }); /** @module ember @submodule ember-htmlbars */ 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, _emberMetalEnvironment, _htmlbarsRuntime, _emberMetalMerge, _emberHtmlbarsHooksSubexpr, _emberHtmlbarsHooksConcat, _emberHtmlbarsHooksLinkRenderNode, _emberHtmlbarsHooksCreateFreshScope, _emberHtmlbarsHooksBindShadowScope, _emberHtmlbarsHooksBindSelf, _emberHtmlbarsHooksBindScope, _emberHtmlbarsHooksBindLocal, _emberHtmlbarsHooksUpdateSelf, _emberHtmlbarsHooksGetRoot, _emberHtmlbarsHooksGetChild, _emberHtmlbarsHooksGetValue, _emberHtmlbarsHooksGetCellOrValue, _emberHtmlbarsHooksCleanupRenderNode, _emberHtmlbarsHooksDestroyRenderNode, _emberHtmlbarsHooksDidRenderNode, _emberHtmlbarsHooksWillCleanupTree, _emberHtmlbarsHooksDidCleanupTree, _emberHtmlbarsHooksClassify, _emberHtmlbarsHooksComponent, _emberHtmlbarsHooksLookupHelper, _emberHtmlbarsHooksHasHelper, _emberHtmlbarsHooksInvokeHelper, _emberHtmlbarsHooksElement, _emberHtmlbarsHelpers, _emberHtmlbarsKeywords, _emberHtmlbarsSystemDomHelper, _emberHtmlbarsKeywordsDebugger, _emberHtmlbarsKeywordsWith, _emberHtmlbarsKeywordsOutlet, _emberHtmlbarsKeywordsReal_outlet, _emberHtmlbarsKeywordsCustomized_outlet, _emberHtmlbarsKeywordsUnbound, _emberHtmlbarsKeywordsView, _emberHtmlbarsKeywordsComponent, _emberHtmlbarsKeywordsPartial, _emberHtmlbarsKeywordsInput, _emberHtmlbarsKeywordsTextarea, _emberHtmlbarsKeywordsCollection, _emberHtmlbarsKeywordsTemplate, _emberHtmlbarsKeywordsLegacyYield, _emberHtmlbarsKeywordsMut, _emberHtmlbarsKeywordsEach, _emberHtmlbarsKeywordsReadonly) { var emberHooks = _emberMetalMerge["default"]({}, _htmlbarsRuntime.hooks); emberHooks.keywords = _emberHtmlbarsKeywords["default"]; _emberMetalMerge["default"](emberHooks, { linkRenderNode: _emberHtmlbarsHooksLinkRenderNode["default"], createFreshScope: _emberHtmlbarsHooksCreateFreshScope["default"], bindShadowScope: _emberHtmlbarsHooksBindShadowScope["default"], bindSelf: _emberHtmlbarsHooksBindSelf["default"], bindScope: _emberHtmlbarsHooksBindScope["default"], bindLocal: _emberHtmlbarsHooksBindLocal["default"], updateSelf: _emberHtmlbarsHooksUpdateSelf["default"], getRoot: _emberHtmlbarsHooksGetRoot["default"], getChild: _emberHtmlbarsHooksGetChild["default"], getValue: _emberHtmlbarsHooksGetValue["default"], getCellOrValue: _emberHtmlbarsHooksGetCellOrValue["default"], subexpr: _emberHtmlbarsHooksSubexpr["default"], concat: _emberHtmlbarsHooksConcat["default"], cleanupRenderNode: _emberHtmlbarsHooksCleanupRenderNode["default"], destroyRenderNode: _emberHtmlbarsHooksDestroyRenderNode["default"], willCleanupTree: _emberHtmlbarsHooksWillCleanupTree["default"], didCleanupTree: _emberHtmlbarsHooksDidCleanupTree["default"], didRenderNode: _emberHtmlbarsHooksDidRenderNode["default"], classify: _emberHtmlbarsHooksClassify["default"], component: _emberHtmlbarsHooksComponent["default"], lookupHelper: _emberHtmlbarsHooksLookupHelper["default"], hasHelper: _emberHtmlbarsHooksHasHelper["default"], invokeHelper: _emberHtmlbarsHooksInvokeHelper["default"], element: _emberHtmlbarsHooksElement["default"] }); _emberHtmlbarsKeywords.registerKeyword("debugger", _emberHtmlbarsKeywordsDebugger["default"]); _emberHtmlbarsKeywords.registerKeyword("with", _emberHtmlbarsKeywordsWith["default"]); _emberHtmlbarsKeywords.registerKeyword("outlet", _emberHtmlbarsKeywordsOutlet["default"]); _emberHtmlbarsKeywords.registerKeyword("@real_outlet", _emberHtmlbarsKeywordsReal_outlet["default"]); _emberHtmlbarsKeywords.registerKeyword("@customized_outlet", _emberHtmlbarsKeywordsCustomized_outlet["default"]); _emberHtmlbarsKeywords.registerKeyword("unbound", _emberHtmlbarsKeywordsUnbound["default"]); _emberHtmlbarsKeywords.registerKeyword("view", _emberHtmlbarsKeywordsView["default"]); _emberHtmlbarsKeywords.registerKeyword("component", _emberHtmlbarsKeywordsComponent["default"]); _emberHtmlbarsKeywords.registerKeyword("partial", _emberHtmlbarsKeywordsPartial["default"]); _emberHtmlbarsKeywords.registerKeyword("template", _emberHtmlbarsKeywordsTemplate["default"]); _emberHtmlbarsKeywords.registerKeyword("input", _emberHtmlbarsKeywordsInput["default"]); _emberHtmlbarsKeywords.registerKeyword("textarea", _emberHtmlbarsKeywordsTextarea["default"]); _emberHtmlbarsKeywords.registerKeyword("collection", _emberHtmlbarsKeywordsCollection["default"]); _emberHtmlbarsKeywords.registerKeyword("legacy-yield", _emberHtmlbarsKeywordsLegacyYield["default"]); _emberHtmlbarsKeywords.registerKeyword("mut", _emberHtmlbarsKeywordsMut["default"]); _emberHtmlbarsKeywords.registerKeyword("@mut", _emberHtmlbarsKeywordsMut.privateMut); _emberHtmlbarsKeywords.registerKeyword("each", _emberHtmlbarsKeywordsEach["default"]); _emberHtmlbarsKeywords.registerKeyword("readonly", _emberHtmlbarsKeywordsReadonly["default"]); exports["default"] = { hooks: emberHooks, helpers: _emberHtmlbarsHelpers["default"], useFragmentCache: true }; var domHelper = _emberMetalEnvironment["default"].hasDOM ? new _emberHtmlbarsSystemDomHelper["default"]() : null; exports.domHelper = domHelper; }); enifed('ember-htmlbars/helper', ['exports', 'ember-runtime/system/object'], function (exports, _emberRuntimeSystemObject) { exports.helper = helper; /** Ember Helpers are functions that can compute values, and are used in templates. For example, this code calls a helper named `format-currency`: ```handlebars
{{format-currency cents currency="$"}}
``` Additionally a helper can be called as a nested helper (sometimes called a subexpression). In this example, the computed value of a helper is passed to a component named `show-money`: ```handlebars {{show-money amount=(format-currency cents currency="$")}} ``` Helpers defined using a class must provide a `compute` function. For example: ```js export default Ember.Helper.extend({ compute(params, hash) { let cents = params[0]; let currency = hash.currency; return `${currency}${cents * 0.01}`; } }); ``` Each time the input to a helper changes, the `compute` function will be called again. As instances, these helpers also have access to the container an will accept injected dependencies. Additionally, class helpers can call `recompute` to force a new computation. @class Ember.Helper @public */ var Helper = _emberRuntimeSystemObject["default"].extend({ isHelper: true, /** On a class-based helper, it may be useful to force a recomputation of that helpers value. This is akin to `rerender` on a component. For example, this component will rerender when the `currentUser` on a session service changes: ```js // app/helpers/current-user-email.js export default Ember.Helper.extend({ session: Ember.inject.service(), onNewUser: Ember.observer('session.currentUser', function() { this.recompute(); }), compute() { return this.get('session.currentUser.email'); } }); ``` @method recompute @public */ recompute: function () { this._stream.notify(); } /** Override this function when writing a class-based helper. @method compute @param {Array} params The positional arguments to the helper @param {Object} hash The named arguments to the helper @public */ }); Helper.reopenClass({ isHelperFactory: true }); /** In many cases, the ceremony of a full `Ember.Helper` class is not required. The `helper` method create pure-function helpers without instances. For example: ```js // app/helpers/format-currency.js export default Ember.Helper.helper(function(params, hash) { let cents = params[0]; let currency = hash.currency; return `${currency}${cents * 0.01}`; }); ``` @static @param {Function} helper The helper function @method helper @public */ function helper(helperFn) { return { isHelperInstance: true, compute: helperFn }; } exports["default"] = Helper; }); /** @module ember @submodule ember-templates */ enifed("ember-htmlbars/helpers", ["exports", "ember-metal/platform/create"], function (exports, _emberMetalPlatformCreate) { exports.registerHelper = registerHelper; /** @private @property helpers */ var helpers = _emberMetalPlatformCreate["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; }); /** @module ember @submodule ember-htmlbars */ enifed('ember-htmlbars/helpers/-bind-attr-class', ['exports', 'ember-metal/property_get', 'ember-metal/utils'], function (exports, _emberMetalProperty_get, _emberMetalUtils) { exports["default"] = bindAttrClassHelper; function bindAttrClassHelper(params) { var value = params[0]; if (_emberMetalUtils.isArray(value)) { value = _emberMetalProperty_get.get(value, 'length') !== 0; } if (value === true) { return params[1]; }if (value === false || value === undefined || value === null) { return ''; } else { return value; } } }); /** @module ember @submodule ember-htmlbars */ enifed('ember-htmlbars/helpers/-concat', ['exports'], function (exports) { exports["default"] = concat; /** Concatenates input params together. Example: ```handlebars {{some-component name=(concat firstName " " lastName)}} {{! would pass name=" " to the component}} ``` @public @method concat @for Ember.HTMLBars */ function concat(params) { return params.join(''); } }); enifed("ember-htmlbars/helpers/-html-safe", ["exports", "htmlbars-util/safe-string"], function (exports, _htmlbarsUtilSafeString) { exports["default"] = htmlSafeHelper; /** This private helper is used internally to handle `isVisible: false` for Ember.View and Ember.Component. @private */ function htmlSafeHelper(_ref) { var value = _ref[0]; return new _htmlbarsUtilSafeString["default"](value); } }); enifed('ember-htmlbars/helpers/-join-classes', ['exports'], function (exports) { exports["default"] = joinClasses; /* this private helper is used to join and compact a list of class names @private */ 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", "ember-htmlbars/utils/decode-each-key"], function (exports, _emberMetalProperty_get, _emberMetalEnumerable_utils, _emberHtmlbarsUtilsNormalizeSelf, _emberHtmlbarsUtilsDecodeEachKey) { exports["default"] = legacyEachWithControllerHelper; function legacyEachWithControllerHelper(params, hash, blocks) { var list = params[0]; var keyPath = hash.key; // TODO: Correct falsy semantics if (!list || _emberMetalProperty_get.get(list, "length") === 0) { if (blocks.inverse.yield) { blocks.inverse.yield(); } return; } _emberMetalEnumerable_utils.forEach(list, function (item, i) { var self; if (blocks.template.arity === 0) { Ember.deprecate(deprecation); self = _emberHtmlbarsUtilsNormalizeSelf["default"](item); self = bindController(self, true); } var key = _emberHtmlbarsUtilsDecodeEachKey["default"](item, keyPath, 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/enumerable_utils", "ember-views/streams/should_display", "ember-htmlbars/utils/decode-each-key"], function (exports, _emberMetalEnumerable_utils, _emberViewsStreamsShould_display, _emberHtmlbarsUtilsDecodeEachKey) { exports["default"] = legacyEachWithKeywordHelper; function legacyEachWithKeywordHelper(params, hash, blocks) { var list = params[0]; var keyPath = hash.key; var legacyKeyword = hash["-legacy-keyword"]; if (_emberViewsStreamsShould_display["default"](list)) { _emberMetalEnumerable_utils.forEach(list, function (item, i) { var self; if (legacyKeyword) { self = bindKeyword(self, legacyKeyword, item); } var key = _emberHtmlbarsUtilsDecodeEachKey["default"](item, keyPath, 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 = { 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, _emberRuntimeSystemString, _emberMetalPath_cache) { exports["default"] = normalizeClass; /* This private helper is used by ComponentNode to convert the classNameBindings microsyntax into a class name. When a component or view is created, we normalize class name bindings into a series of attribute nodes that use this helper. @private */ 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 && _emberMetalPath_cache.isPath(propName)) { var segments = propName.split("."); propName = segments[segments.length - 1]; } return _emberRuntimeSystemString.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", ["exports"], function (exports) {}); /** @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 {Object} options @return {String} HTML string @public */ /** See `bind-attr` @method bindAttr @for Ember.Handlebars.helpers @deprecated @param {Function} context @param {Object} options @return {String} HTML string @public */ enifed('ember-htmlbars/helpers/each', ['exports', 'ember-metal/core', 'ember-metal/error', 'ember-metal/enumerable_utils', 'ember-htmlbars/utils/normalize-self', 'ember-views/streams/should_display', 'ember-htmlbars/utils/decode-each-key'], function (exports, _emberMetalCore, _emberMetalError, _emberMetalEnumerable_utils, _emberHtmlbarsUtilsNormalizeSelf, _emberViewsStreamsShould_display, _emberHtmlbarsUtilsDecodeEachKey) { exports["default"] = eachHelper; /** The `{{#each}}` helper loops over elements in a collection. It is an extension of the base Handlebars `{{#each}}` helper. The default behavior of `{{#each}}` is to yield its inner block once for every item in an array. ```javascript var developers = [{name: 'Yehuda'},{name: 'Tom'}, {name: 'Paul'}]; ``` ```handlebars {{#each developers key="name" as |person|}} {{person.name}} {{! `this` is whatever it was outside the #each }} {{/each}} ``` The same rules apply to arrays of primitives. ```javascript var developerNames = ['Yehuda', 'Tom', 'Paul'] ``` ```handlebars {{#each developerNames key="@index" as |name|}} {{name}} {{/each}} ``` ### Specifying Keys The `key` option is used to tell Ember how to determine if the array being iterated over with `{{#each}}` has changed between renders. By helping Ember detect that some elements in the array are the same, DOM elements can be re-used, significantly improving rendering speed. For example, here's the `{{#each}}` helper with its `key` set to `id`: ```handlebars {{#each model key="id" as |item|}} {{/each}} ``` When this `{{#each}}` re-renders, Ember will match up the previously rendered items (and reorder the generated DOM elements) based on each item's `id` property. By default the item's own reference is used. ### {{else}} condition `{{#each}}` can have a matching `{{else}}`. The contents of this block will render if the collection is empty. ```handlebars {{#each developers as |person|}} {{person.name}} {{else}}

Sorry, nobody is available for this task.

{{/each}} ``` @method each @for Ember.Templates.helpers @public */ function eachHelper(params, hash, blocks) { var list = params[0]; var keyPath = hash.key; if (blocks.template.arity === 0) { _emberMetalCore["default"].deprecate(deprecation); } if (_emberViewsStreamsShould_display["default"](list)) { (function () { var seenKeys = {}; _emberMetalEnumerable_utils.forEach(list, function (item, i) { var self; if (blocks.template.arity === 0) { self = _emberHtmlbarsUtilsNormalizeSelf["default"](item); } var key = _emberHtmlbarsUtilsDecodeEachKey["default"](item, keyPath, i); if (seenKeys[key] === true) { throw new _emberMetalError["default"]('Duplicate key found (\'' + key + '\') for \'{{each}}\' helper, please use a unique key or switch to \'{{#each model key="@index"}}{{/each}}\'.'); } else { seenKeys[key] = true; } 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, _emberMetalCore, _emberViewsStreamsShould_display) { /** Use the `if` block helper to conditionally render a block depending on a property. If the property is "falsey", for example: `false`, `undefined `null`, `""`, `0` or an empty array, the block will not be rendered. ```handlebars {{! will not render if foo is falsey}} {{#if foo}} Welcome to the {{foo.bar}} {{/if}} ``` You can also specify a template to show if the property is falsey by using the `else` helper. ```handlebars {{!Is it raining outside?}} {{#if isRaining}} Yes, grab an umbrella! {{else}} No, it's lovely outside! {{/if}} ``` You are also able to combine `else` and `if` helpers to create more complex conditional logic. ```handlebars {{#if isMorning}} Good morning {{else if isAfternoon}} Good afternoon {{else}} Good night {{/if}} ``` You can use `if` inline to conditionally render a single property or string. This helper acts like a ternary operator. If the first property is truthy, the second argument will be displayed, if not, the third argument will be displayed ```handlebars {{if useLongGreeting "Hello" "Hi"}} Dave ``` Finally, you can use the `if` helper inside another helper as a subexpression. ```handlebars {{some-component height=(if isBig "100" "10")}} ``` @method if @for Ember.Templates.helpers @public */ function ifHelper(params, hash, options) { return ifUnless(params, hash, options, _emberViewsStreamsShould_display["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.Templates.helpers @public */ function unlessHelper(params, hash, options) { return ifUnless(params, hash, options, !_emberViewsStreamsShould_display["default"](params[0])); } function ifUnless(params, hash, options, truthy) { _emberMetalCore["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); _emberMetalCore["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]; } } } exports.ifHelper = ifHelper; exports.unlessHelper = unlessHelper; }); /** @module ember @submodule ember-templates */ // Ember.assert enifed('ember-htmlbars/helpers/loc', ['exports', 'ember-runtime/system/string'], function (exports, _emberRuntimeSystemString) { exports["default"] = locHelper; /** @module ember @submodule ember-templates */ /** Calls [Ember.String.loc](/api/classes/Ember.String.html#method_loc) with the provided string. This is a convenient way to localize text within a template. For example: ```javascript Ember.STRINGS = { '_welcome_': 'Bonjour' }; ``` ```handlebars
{{loc '_welcome_'}}
``` ```html
Bonjour
``` See [Ember.String.loc](/api/classes/Ember.String.html#method_loc) for how to set up localized string references. @method loc @for Ember.Templates.helpers @param {String} str The string to format @see {Ember.String#loc} @public */ function locHelper(params) { return _emberRuntimeSystemString.loc.apply(null, params); } }); enifed("ember-htmlbars/helpers/log", ["exports", "ember-metal/logger"], function (exports, _emberMetalLogger) { exports["default"] = logHelper; /** `log` allows you to output the value of variables in the current rendering context. `log` also accepts primitive types such as strings or numbers. ```handlebars {{log "myVariable:" myVariable }} ``` @method log @for Ember.Templates.helpers @param {*} values @public */ function logHelper(values) { _emberMetalLogger["default"].log.apply(null, values); } }); /** @module ember @submodule ember-templates */ enifed("ember-htmlbars/helpers/with", ["exports", "ember-htmlbars/utils/normalize-self", "ember-views/streams/should_display"], function (exports, _emberHtmlbarsUtilsNormalizeSelf, _emberViewsStreamsShould_display) { exports["default"] = withHelper; /** Use the `{{with}}` helper when you want to alias a property to a new name. This is helpful for semantic clarity as it allows you to retain default scope or to reference a property from another `{{with}}` block. If the aliased property is "falsey", for example: `false`, `undefined` `null`, `""`, `0` or an empty array, the block will not be rendered. ```handlebars {{! Will only render if user.posts contains items}} {{#with user.posts as |blogPosts|}}
There are {{blogPosts.length}} blog posts written by {{user.name}}.
{{#each blogPosts as |post|}}
  • {{post.title}}
  • {{/each}} {{/with}} ``` Without the `as` operator, it would be impossible to reference `user.name` in the example above. NOTE: The alias should not reuse a name from the bound property path. For example: `{{#with foo.bar as |foo|}}` is not supported because it attempts to alias using the first part of the property path, `foo`. Instead, use `{{#with foo.bar as |baz|}}`. @method with @for Ember.Templates.helpers @param {Object} options @return {String} HTML string @public */ function withHelper(params, hash, options) { if (_emberViewsStreamsShould_display["default"](params[0])) { var preserveContext = false; if (options.template.arity !== 0) { preserveContext = true; } if (preserveContext) { this.yield([params[0]]); } else { var _self = _emberHtmlbarsUtilsNormalizeSelf["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([]); } } }); /** @module ember @submodule ember-templates */ enifed("ember-htmlbars/hooks/bind-local", ["exports", "ember-metal/streams/stream", "ember-metal/streams/proxy-stream"], function (exports, _emberMetalStreamsStream, _emberMetalStreamsProxyStream) { exports["default"] = bindLocal; 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); } } else { var newValue = _emberMetalStreamsStream["default"].wrap(value, _emberMetalStreamsProxyStream["default"], key); scope.locals[key] = newValue; } } }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/hooks/bind-scope", ["exports"], function (exports) { 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, _emberMetalStreamsProxyStream, _emberHtmlbarsUtilsSubscribe) { exports["default"] = bindSelf; 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) { 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 _emberMetalStreamsProxyStream["default"](newValue, isSelf ? "" : key); if (renderNode) { _emberHtmlbarsUtilsSubscribe["default"](renderNode, scope, stream); } scope[key] = stream; } }); /** @module ember @submodule ember-htmlbars */ enifed('ember-htmlbars/hooks/bind-shadow-scope', ['exports', 'ember-views/views/component', 'ember-metal/streams/proxy-stream', 'ember-htmlbars/utils/subscribe'], function (exports, _emberViewsViewsComponent, _emberMetalStreamsProxyStream, _emberHtmlbarsUtilsSubscribe) { exports["default"] = bindShadowScope; 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 _emberViewsViewsComponent["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 _emberMetalStreamsProxyStream["default"](newValue, isSelf ? '' : key); if (renderNode) { _emberHtmlbarsUtilsSubscribe["default"](renderNode, scope, stream); } scope[key] = stream; } }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/hooks/classify", ["exports", "ember-htmlbars/utils/is-component"], function (exports, _emberHtmlbarsUtilsIsComponent) { exports["default"] = classify; function classify(env, scope, path) { if (_emberHtmlbarsUtilsIsComponent["default"](env, scope, path)) { return "component"; } return null; } }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/hooks/cleanup-render-node", ["exports"], function (exports) { 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, _emberHtmlbarsNodeManagersComponentNodeManager) { 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 parentView = env.view; var manager = _emberHtmlbarsNodeManagersComponentNodeManager["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, _emberMetalStreamsUtils) { exports["default"] = concat; function concat(env, parts) { return _emberMetalStreamsUtils.concat(parts, ""); } }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/hooks/create-fresh-scope", ["exports"], function (exports) { exports["default"] = createFreshScope; /* Ember's implementation of HTMLBars creates an enriched scope. * self: same as HTMLBars, this field represents the dynamic lookup of root keys that are not special keywords or block arguments. * blocks: same as HTMLBars, a bundle of named blocks the layout can yield to. * component: indicates that the scope is the layout of a component, which is used to trigger lifecycle hooks for the component when one of the streams in its layout fires. * attrs: a map of key-value attributes sent in by the invoker of a template, and available in the component's layout. * locals: a map of locals, produced by block params (`as |a b|`) * localPresent: a map of available locals to avoid expensive `hasOwnProperty` checks. The `self` field has two special meanings: * If `self` is a view (`isView`), the actual HTMLBars `self` becomes the view's `context`. This is legacy semantics; components always use the component itself as the `this`. * If `self` is a view, two special locals are created: `view` and `controller`. These locals are legacy semantics. * If self has a `hasBoundController` property, it is coming from a legacy form of #with or #each (`{{#with something controller=someController}}`). This has the special effect of giving the child scope the supplied `controller` keyword, with an unrelated `self`. This is legacy functionality, as both the `view` and `controller` keywords have been deprecated. **IMPORTANT**: There are two places in Ember where the ambient controller is looked up. Both of those places use the presence of `scope.locals.view` to indicate that the controller lookup should be dynamic off of the ambient view. If `scope.locals.view` does not exist, the code assumes that it is inside of a top-level template (without a view) and uses the `self` itself as the controller. This means that if you remove `scope.locals.view` (perhaps because we are finally ready to shed the view keyword), there may be unexpected consequences on controller semantics. If this happens to you, I hope you find this comment. - YK & TD In practice, this means that with the exceptions of top-level view-less templates and the legacy `controller=foo` semantics, the controller hierarchy is managed dynamically by looking at the current view's `controller`. */ function createFreshScope() { return { self: null, blocks: {}, component: null, attrs: null, locals: {}, localPresent: {} }; } }); enifed("ember-htmlbars/hooks/destroy-render-node", ["exports"], function (exports) { 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) { exports["default"] = didCleanupTree; function didCleanupTree(env) { // Once we have finsihed cleaning up the render node and sub-nodes, reset // state tracking which view those render nodes belonged to. env.view.ownerView._destroyingSubtreeForView = null; } }); enifed("ember-htmlbars/hooks/did-render-node", ["exports"], function (exports) { 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", "ember-htmlbars/system/invoke-helper"], function (exports, _emberHtmlbarsSystemLookupHelper, _htmlbarsRuntimeHooks, _emberHtmlbarsSystemInvokeHelper) { exports["default"] = emberElement; 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 (_htmlbarsRuntimeHooks.handleRedirect(morph, env, scope, path, params, hash, null, null, visitor)) { return; } var result; var helper = _emberHtmlbarsSystemLookupHelper.findHelper(path, scope.self, env); if (helper) { var helperStream = _emberHtmlbarsSystemInvokeHelper.buildHelperStream(helper, params, hash, { element: morph.element }, env, scope); result = helperStream.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); } } }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/hooks/get-cell-or-value", ["exports", "ember-metal/streams/utils", "ember-htmlbars/keywords/mut"], function (exports, _emberMetalStreamsUtils, _emberHtmlbarsKeywordsMut) { exports["default"] = getCellOrValue; function getCellOrValue(ref) { if (ref && ref[_emberHtmlbarsKeywordsMut.MUTABLE_REFERENCE]) { // reify the mutable reference into a mutable cell return ref.cell(); } // get the value out of the reference return _emberMetalStreamsUtils.read(ref); } }); enifed("ember-htmlbars/hooks/get-child", ["exports", "ember-metal/streams/utils"], function (exports, _emberMetalStreamsUtils) { exports["default"] = getChild; function getChild(parent, key) { if (_emberMetalStreamsUtils.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]; } }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/hooks/get-root", ["exports", "ember-metal/core", "ember-metal/path_cache", "ember-metal/streams/proxy-stream"], function (exports, _emberMetalCore, _emberMetalPath_cache, _emberMetalStreamsProxyStream) { exports["default"] = getRoot; 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 (_emberMetalPath_cache.isGlobal(key) && _emberMetalCore["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 (self) { return self.getKey(key); } else 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]; } } function getGlobal(name) { _emberMetalCore["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 _emberMetalStreamsProxyStream["default"](_emberMetalCore["default"].lookup[name], name); } }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/hooks/get-value", ["exports", "ember-metal/streams/utils", "ember-views/compat/attrs-proxy"], function (exports, _emberMetalStreamsUtils, _emberViewsCompatAttrsProxy) { exports["default"] = getValue; function getValue(ref) { var value = _emberMetalStreamsUtils.read(ref); if (value && value[_emberViewsCompatAttrsProxy.MUTABLE_CELL]) { return value.value; } return value; } }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/hooks/has-helper", ["exports", "ember-htmlbars/system/lookup-helper"], function (exports, _emberHtmlbarsSystemLookupHelper) { exports["default"] = hasHelperHook; function hasHelperHook(env, scope, helperName) { if (env.helpers[helperName]) { return true; } var container = env.container; if (_emberHtmlbarsSystemLookupHelper.validateLazyHelperName(helperName, container, env.hooks.keywords, env.knownHelpers)) { var containerName = "helper:" + helperName; if (container._registry.has(containerName)) { return true; } } return false; } }); enifed("ember-htmlbars/hooks/invoke-helper", ["exports", "ember-metal/core", "ember-htmlbars/system/invoke-helper", "ember-htmlbars/utils/subscribe"], function (exports, _emberMetalCore, _emberHtmlbarsSystemInvokeHelper, _emberHtmlbarsUtilsSubscribe) { exports["default"] = invokeHelper; function invokeHelper(morph, env, scope, visitor, params, hash, helper, templates, context) { if (helper.isLegacyViewHelper) { _emberMetalCore["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); // Opts into a special mode for view helpers return { handled: true }; } var helperStream = _emberHtmlbarsSystemInvokeHelper.buildHelperStream(helper, params, hash, templates, env, scope, context); // Ember.Helper helpers are pure values, thus linkable if (helperStream.linkable) { if (morph) { // When processing an inline expression the params and hash have already // been linked. Thus, HTMLBars will not link the returned helperStream. // We subscribe the morph to the helperStream here, and also subscribe // the helperStream to any params. var addedDependency = false; for (var i = 0, l = params.length; i < l; i++) { addedDependency = true; helperStream.addDependency(params[i]); } for (var key in hash) { addedDependency = true; helperStream.addDependency(hash[key]); } if (addedDependency) { _emberHtmlbarsUtilsSubscribe["default"](morph, env, scope, helperStream); } } return { link: true, value: helperStream }; } // Legacy helpers are not linkable, they must run every rerender return { value: helperStream.value() }; } }); // Ember.assert 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, _emberHtmlbarsUtilsSubscribe, _emberRuntimeUtils, _emberMetalStreamsUtils, _emberHtmlbarsSystemLookupHelper) { exports["default"] = linkRenderNode; 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 "unless": case "if": params[0] = shouldDisplay(params[0]);break; case "each": params[0] = eachParam(params[0]);break; default: helper = _emberHtmlbarsSystemLookupHelper.findHelper(path, env.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++) { _emberHtmlbarsUtilsSubscribe["default"](renderNode, env, scope, params[i]); } } if (hash) { for (var key in hash) { _emberHtmlbarsUtilsSubscribe["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 = _emberMetalStreamsUtils.chain(list, function () { _emberMetalStreamsUtils.read(listChange); return _emberMetalStreamsUtils.read(list); }, "each"); stream.addDependency(listChange); return stream; } function shouldDisplay(predicate) { var length = getKey(predicate, "length"); var isTruthy = getKey(predicate, "isTruthy"); var stream = _emberMetalStreamsUtils.chain(predicate, function () { var predicateVal = _emberMetalStreamsUtils.read(predicate); var lengthVal = _emberMetalStreamsUtils.read(length); var isTruthyVal = _emberMetalStreamsUtils.read(isTruthy); if (_emberRuntimeUtils.isArray(predicateVal)) { return lengthVal > 0; } if (typeof isTruthyVal === "boolean") { return isTruthyVal; } return !!predicateVal; }, "ShouldDisplay"); _emberMetalStreamsUtils.addDependency(stream, length); _emberMetalStreamsUtils.addDependency(stream, isTruthy); return stream; } function getKey(obj, key) { if (_emberMetalStreamsUtils.isStream(obj)) { return obj.getKey(key); } else { return obj && obj[key]; } } function processHandlebarsCompatDepKeys(base, additionalKeys) { if (!_emberMetalStreamsUtils.isStream(base) || additionalKeys.length === 0) { return base; } var depKeyStreams = []; var stream = _emberMetalStreamsUtils.chain(base, function () { _emberMetalStreamsUtils.readArray(depKeyStreams); return _emberMetalStreamsUtils.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; } }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/hooks/lookup-helper", ["exports", "ember-htmlbars/system/lookup-helper"], function (exports, _emberHtmlbarsSystemLookupHelper) { exports["default"] = lookupHelperHook; function lookupHelperHook(env, scope, helperName) { return _emberHtmlbarsSystemLookupHelper["default"](helperName, scope.self, env); } }); enifed("ember-htmlbars/hooks/subexpr", ["exports", "ember-htmlbars/system/lookup-helper", "ember-htmlbars/system/invoke-helper", "ember-metal/streams/utils"], function (exports, _emberHtmlbarsSystemLookupHelper, _emberHtmlbarsSystemInvokeHelper, _emberMetalStreamsUtils) { exports["default"] = subexpr; 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 label = labelForSubexpr(params, hash, helperName); var helper = _emberHtmlbarsSystemLookupHelper["default"](helperName, scope.self, env); var helperStream = _emberHtmlbarsSystemInvokeHelper.buildHelperStream(helper, params, hash, { template: {}, inverse: {} }, env, scope, label); for (var i = 0, l = params.length; i < l; i++) { helperStream.addDependency(params[i]); } for (var key in hash) { helperStream.addDependency(hash[key]); } return helperStream; } 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 _emberMetalStreamsUtils.labelsFor(params).join(" "); } function labelsForHash(hash) { var out = []; for (var prop in hash) { out.push(prop + "=" + _emberMetalStreamsUtils.labelFor(hash[prop])); } return out.join(" "); } }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/hooks/update-self", ["exports", "ember-metal/property_get", "ember-htmlbars/utils/update-scope"], function (exports, _emberMetalProperty_get, _emberHtmlbarsUtilsUpdateScope) { exports["default"] = updateSelf; function updateSelf(env, scope, _self) { var self = _self; if (self && self.hasBoundController) { var controller = self.controller; self = self.self; _emberHtmlbarsUtilsUpdateScope["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) { _emberHtmlbarsUtilsUpdateScope["default"](scope.locals, "view", self, null); _emberHtmlbarsUtilsUpdateScope["default"](scope, "self", _emberMetalProperty_get.get(self, "context"), null, true); return; } _emberHtmlbarsUtilsUpdateScope["default"](scope, "self", self, null); } }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/hooks/will-cleanup-tree", ["exports"], function (exports) { exports["default"] = willCleanupTree; function willCleanupTree(env) { var view = env.view; // When we go to clean up the render node and all of its children, we may // encounter views/components associated with those nodes along the way. In // those cases, we need to make sure we need to sever the link between the // existing view hierarchy and those views. // // However, we do *not* need to remove the child views of child views, since // severing the connection to their parent effectively severs them from the // view graph. // // For example, imagine the following view graph: // // A // / \ // B C // / \ // D E // // If we are cleaning up the node for view C, we need to remove that view // from A's child views. However, we do not need to remove D and E from C's // child views, since removing C transitively removes D and E as well. // // To accomplish this, we track the nearest view to this render node on the // owner view, the root-most view in the graph (A in the example above). If // we detect a view that is a direct child of that view, we remove it from // the `childViews` array. Other parent/child view relationships are // untouched. This view is then cleared once cleanup is complete in // `didCleanupTree`. view.ownerView._destroyingSubtreeForView = view; } }); enifed("ember-htmlbars/keywords", ["exports", "htmlbars-runtime", "ember-metal/platform/create"], function (exports, _htmlbarsRuntime, _emberMetalPlatformCreate) { exports.registerKeyword = registerKeyword; /** @private @property helpers */ var keywords = _emberMetalPlatformCreate["default"](_htmlbarsRuntime.hooks.keywords); /** @module ember @submodule ember-htmlbars */ /** @private @method _registerHelper @for Ember.HTMLBars @param {String} name @param {Object|Function} keyword the keyword to add */ function registerKeyword(name, keyword) { keywords[name] = keyword; } exports["default"] = keywords; }); /** @module ember @submodule ember-htmlbars */ 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, _emberViewsStreamsUtils, _emberViewsViewsCollection_view, _emberHtmlbarsNodeManagersViewNodeManager, _emberMetalKeys, _emberMetalMerge) { exports["default"] = { setupState: function (state, env, scope, params, hash) { var read = env.hooks.getValue; return _emberMetalMerge.assign({}, state, { parentView: env.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 (_emberMetalKeys["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 = _emberHtmlbarsNodeManagersViewNodeManager["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 = _emberViewsViewsCollection_view["default"]; } else { viewClassOrInstance = _emberViewsStreamsUtils.readViewFactory(viewPath, container); } return viewClassOrInstance; } }); /** @module ember @submodule ember-htmlbars */ enifed('ember-htmlbars/keywords/component', ['exports', 'ember-metal/merge'], function (exports, _emberMetalMerge) { /** The `{{component}}` helper lets you add instances of `Ember.Component` to a template. See [Ember.Component](/api/classes/Ember.Component.html) for additional information on how a `Component` functions. `{{component}}`'s primary use is for cases where you want to dynamically change which type of component is rendered as the state of your application changes. The provided block will be applied as the template for the component. Given an empty `` the following template: ```handlebars {{! application.hbs }} {{component infographicComponentName}} ``` And the following application code: ```javascript export default Ember.Controller.extend({ infographicComponentName: computed('isMarketOpen', { get() { if (this.get('isMarketOpen')) { return 'live-updating-chart'; } else { return 'market-close-summary'; } } }) }); ``` The `live-updating-chart` component will be appended when `isMarketOpen` is `true`, and the `market-close-summary` component will be appended when `isMarketOpen` is `false`. If the value changes while the app is running, the component will be automatically swapped out accordingly. Note: You should not use this helper when you are consistently rendering the same component. In that case, use standard component syntax, for example: ```handlebars {{! application.hbs }} {{live-updating-chart}} ``` @method component @since 1.11.0 @for Ember.Templates.helpers @public */ exports["default"] = { setupState: function (lastState, env, scope, params, hash) { var componentPath = env.hooks.getValue(params[0]); return _emberMetalMerge.assign({}, lastState, { componentPath: componentPath, isComponentHelper: true }); }, render: function (morph) { if (morph.state.manager) { morph.state.manager.destroy(); } // 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; for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { rest[_key - 1] = arguments[_key]; } 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); } }); /** @module ember @submodule ember-templates @public */ enifed("ember-htmlbars/keywords/customized_outlet", ["exports", "ember-htmlbars/node-managers/view-node-manager", "ember-views/streams/utils", "ember-metal/streams/utils"], function (exports, _emberHtmlbarsNodeManagersViewNodeManager, _emberViewsStreamsUtils, _emberMetalStreamsUtils) { exports["default"] = { setupState: function (state, env, scope, params, hash) { Ember.assert("Using a quoteless view parameter with {{outlet}} is not supported", !hash.view || !_emberMetalStreamsUtils.isStream(hash.view)); var read = env.hooks.getValue; var viewClass = read(hash.viewClass) || _emberViewsStreamsUtils.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 = _emberHtmlbarsNodeManagersViewNodeManager["default"].create(renderNode, env, hash, options, parentView, null, null, null); state.manager = nodeManager; nodeManager.render(env, hash, visitor); } }; }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/keywords/debugger", ["exports", "ember-metal/logger"], function (exports, _emberMetalLogger) { exports["default"] = debuggerKeyword; /** Execute the `debugger` statement in the current template's context. ```handlebars {{debugger}} ``` When using the debugger helper you will have access to a `get` function. This function retrieves values available in the context of the template. For example, if you're wondering why a value `{{foo}}` isn't rendering as expected within a template, you could place a `{{debugger}}` statement and, when the `debugger;` breakpoint is hit, you can attempt to retrieve this value: ``` > get('foo') ``` `get` is also aware of keywords. So in this situation ```handlebars {{#each items as |item|}} {{debugger}} {{/each}} ``` You'll be able to get values from the current item: ``` > get('item.name') ``` You can also access the context of the view to make sure it is the object that you expect: ``` > context ``` @method debugger @for Ember.Templates.helpers @public */ 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)); } _emberMetalLogger["default"].info("Use `view`, `context`, and `get()` to debug this template."); debugger; return true; } }); /*jshint debug:true*/ /** @module ember @submodule ember-htmlbars */ enifed('ember-htmlbars/keywords/each', ['exports', 'ember-runtime/controllers/array_controller'], function (exports, _emberRuntimeControllersArray_controller) { exports["default"] = each; 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 _emberRuntimeControllersArray_controller["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; } }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/keywords/input", ["exports", "ember-metal/core", "ember-metal/merge"], function (exports, _emberMetalCore, _emberMetalMerge) { exports["default"] = { setupState: function (lastState, env, scope, params, hash) { var type = env.hooks.getValue(hash.type); var componentName = componentNameMap[type] || defaultComponentName; _emberMetalCore["default"].assert("{{input type='checkbox'}} does not support setting `value=someBooleanValue`;" + " you must use `checked=someBooleanValue` instead.", !(type === "checkbox" && hash.hasOwnProperty("value"))); return _emberMetalMerge.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 () { this.render.apply(this, arguments); } }; var defaultComponentName = "-text-field"; var componentNameMap = { "checkbox": "-checkbox" }; }); enifed("ember-htmlbars/keywords/legacy-yield", ["exports", "ember-metal/streams/proxy-stream"], function (exports, _emberMetalStreamsProxyStream) { 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 _emberMetalStreamsProxyStream["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, _emberMetalPlatformCreate, _emberMetalMerge, _emberMetalUtils, _emberMetalStreamsProxyStream, _emberMetalStreamsUtils, _emberMetalStreamsStream, _emberViewsCompatAttrsProxy, _emberRoutingHtmlbarsKeywordsClosureAction) { var _merge; exports["default"] = mut; exports.privateMut = privateMut; var MUTABLE_REFERENCE = _emberMetalUtils.symbol("MUTABLE_REFERENCE"); exports.MUTABLE_REFERENCE = 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 (!_emberMetalStreamsUtils.isStream(stream)) { (function () { var literal = stream; stream = new _emberMetalStreamsStream["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", _emberMetalStreamsUtils.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 = _emberMetalPlatformCreate["default"](_emberMetalStreamsProxyStream["default"].prototype); _emberMetalMerge["default"](MutStream.prototype, (_merge = { cell: function () { var source = this; var value = source.value(); if (value && value[_emberRoutingHtmlbarsKeywordsClosureAction.ACTION]) { return value; } var val = { value: value, update: function (val) { source.setValue(val); } }; val[_emberViewsCompatAttrsProxy.MUTABLE_CELL] = true; return val; } }, _merge[_emberRoutingHtmlbarsKeywordsClosureAction.INVOKE] = function (val) { this.setValue(val); }, _merge)); }); enifed('ember-htmlbars/keywords/outlet', ['exports', 'htmlbars-runtime/hooks'], function (exports, _htmlbarsRuntimeHooks) { /* This level of delegation handles backward-compatibility with the `view` parameter to {{outlet}}. When we drop support for the `view` parameter in 2.0, this keyword should just get replaced directly with @real_outlet. */ 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.'); _htmlbarsRuntimeHooks.keyword('@customized_outlet', morph, env, scope, params, hash, template, inverse, visitor); } else { _htmlbarsRuntimeHooks.keyword('@real_outlet', morph, env, scope, params, hash, template, inverse, visitor); } return true; }; }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/keywords/partial", ["exports", "ember-views/system/lookup_partial", "htmlbars-runtime"], function (exports, _emberViewsSystemLookup_partial, _htmlbarsRuntime) { 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 = _emberViewsSystemLookup_partial["default"](env, state.partialName); if (!found) { return true; } _htmlbarsRuntime.internal.hostBlock(renderNode, env, scope, found.raw, null, null, visitor, function (options) { options.templates.template.yield(); }); } }; }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/keywords/readonly", ["exports", "ember-htmlbars/keywords/mut"], function (exports, _emberHtmlbarsKeywordsMut) { 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[_emberHtmlbarsKeywordsMut.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, _emberMetalProperty_get, _emberHtmlbarsNodeManagersViewNodeManager, _emberHtmlbarsTemplatesTopLevelView) { _emberHtmlbarsTemplatesTopLevelView["default"].meta.revision = "Ember@1.13.4"; 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 = _emberHtmlbarsTemplatesTopLevelView["default"]; } return { outletState: selectedOutletState, hasParentOutlet: env.hasParentOutlet, manager: state.manager }; }, childEnv: function (state, env) { return env.childWithOutletState(state.outletState && state.outletState.outlets, 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 = _emberMetalProperty_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 }); } if (state.manager) { state.manager.destroy(); state.manager = null; } if (state.manager) { state.manager.destroy(); state.manager = null; } var nodeManager = _emberHtmlbarsNodeManagersViewNodeManager["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; } }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/keywords/template", ["exports", "ember-metal/core"], function (exports, _emberMetalCore) { exports["default"] = templateKeyword; var deprecation = "The `template` helper has been deprecated in favor of the `partial` helper."; exports.deprecation = deprecation; function templateKeyword(morph, env, scope, params, hash, template, inverse, visitor) { _emberMetalCore["default"].deprecate(deprecation); env.hooks.keyword("partial", morph, env, scope, params, hash, template, inverse, visitor); return true; } }); enifed('ember-htmlbars/keywords/textarea', ['exports'], function (exports) { 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, _emberMetalMerge, _emberMetalPlatformCreate, _emberMetalStreamsStream, _emberMetalStreamsUtils) { exports["default"] = unbound; /** @module ember @submodule ember-htmlbars */ 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 = _emberMetalPlatformCreate["default"](_emberMetalStreamsStream["default"].prototype); _emberMetalMerge["default"](VolatileStream.prototype, { value: function () { return _emberMetalStreamsUtils.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, _emberViewsStreamsUtils, _emberViewsViewsView, _emberHtmlbarsNodeManagersViewNodeManager, _emberMetalKeys) { 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.locals.view ? null : read(scope.self); return { manager: state.manager, parentView: env.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 (_emberMetalKeys["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; } if (state.manager) { state.manager.destroy(); state.manager = null; } var nodeManager = _emberHtmlbarsNodeManagersViewNodeManager["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 = _emberViewsViewsView["default"]; } } else { viewClassOrInstance = _emberViewsStreamsUtils.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; } }); /** @module ember @submodule ember-htmlbars */ enifed('ember-htmlbars/keywords/with', ['exports', 'ember-metal/core', 'ember-metal/property_get', 'htmlbars-runtime', 'ember-metal/streams/utils'], function (exports, _emberMetalCore, _emberMetalProperty_get, _htmlbarsRuntime, _emberMetalStreamsUtils) { 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 = null; if (scope.locals.controller) { parentController = _emberMetalStreamsUtils.read(scope.locals.controller); } else if (scope.locals.view) { parentController = _emberMetalProperty_get.get(_emberMetalStreamsUtils.read(scope.locals.view), 'context'); } 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; } _emberMetalCore["default"].assert('{{#with foo}} must be called with a single argument or the use the ' + '{{#with foo as bar}} syntax', params.length === 1); _emberMetalCore["default"].assert('The {{#with}} helper must be called with a block', !!template); if (template && template.arity === 0) { _emberMetalCore["default"].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' }); } _htmlbarsRuntime.internal.continueBlock(morph, env, scope, 'with', params, hash, template, inverse, visitor); }, rerender: function (morph, env, scope, params, hash, template, inverse, visitor) { _htmlbarsRuntime.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, _emberMetalCore, _domHelper, _emberMetalPlatformCreate) { 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."; exports.styleWarning = styleWarning; function EmberAttrMorph(element, attrName, domHelper, namespace) { HTMLBarsAttrMorph.call(this, element, attrName, domHelper, namespace); this.streamUnsubscribers = null; } var proto = EmberAttrMorph.prototype = _emberMetalPlatformCreate["default"](HTMLBarsAttrMorph.prototype); proto.HTMLBarsAttrMorph$setContent = HTMLBarsAttrMorph.prototype.setContent; proto._deprecateEscapedStyle = function EmberAttrMorph_deprecateEscapedStyle(value) { _emberMetalCore["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; }); enifed("ember-htmlbars/morphs/morph", ["exports", "dom-helper", "ember-metal/platform/create"], function (exports, _domHelper, _emberMetalPlatformCreate) { var HTMLBarsMorph = _domHelper["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 = _emberMetalPlatformCreate["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 = this.emberView; if (view) { var parentView = view.parentView; if (parentView && view.ownerView._destroyingSubtreeForView === parentView) { 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-metal/streams/stream", "ember-metal/streams/utils", "ember-htmlbars/hooks/get-value"], function (exports, _emberMetalCore, _emberMetalMerge, _emberViewsSystemBuildComponentTemplate, _emberHtmlbarsUtilsLookupComponent, _emberHtmlbarsHooksGetCellOrValue, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalSet_properties, _emberViewsCompatAttrsProxy, _htmlbarsUtilSafeString, _emberHtmlbarsSystemInstrumentationSupport, _emberViewsViewsComponent, _emberMetalStreamsStream, _emberMetalStreamsUtils, _emberHtmlbarsHooksGetValue) { 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 = _emberHtmlbarsUtilsLookupComponent["default"](env.container, tagName); var component = _lookupComponent.component; var layout = _lookupComponent.layout; _emberMetalCore["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 || _emberViewsViewsComponent["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 = _emberHtmlbarsHooksGetValue["default"](parentScope.locals.controller); } // this flag is set when a block was provided so that components can see if // `this.get('template')` is truthy. this is added for backwards compat only // and accessing `template` prop on a component will trigger a deprecation // 2.0TODO: remove if (templates["default"]) { createOptions._deprecatedFlagForBlockProvided = true; } // 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 = _emberViewsSystemBuildComponentTemplate["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) { (function () { // 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 positionalParams = component.positionalParams; var isNamed = typeof positionalParams === "string"; var paramsStream = undefined; if (isNamed) { paramsStream = new _emberMetalStreamsStream["default"](function () { return _emberMetalStreamsUtils.readArray(params.slice(paramsStartIndex)); }, "params"); attrs[positionalParams] = paramsStream; } for (var i = 0; i < positionalParams.length; i++) { var param = params[paramsStartIndex + i]; if (isNamed) { paramsStream.addDependency(param); } else { attrs[positionalParams[i]] = param; } } })(); } } 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 = _emberMetalProperty_get.get(component, "layout"); var hasBlock = _templates && _templates["default"]; var layout = undefined, templates = undefined, componentTemplate = undefined; if (hasBlock) { componentTemplate = null; } else if (component.isComponent) { componentTemplate = _emberMetalProperty_get.get(component, "_template"); } else { componentTemplate = _emberMetalProperty_get.get(component, "template"); } 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; _emberMetalCore["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) { _emberMetalCore["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 = _emberHtmlbarsHooksGetValue["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 = _emberHtmlbarsHooksGetValue["default"](attrs.id); } if (attrs._defaultTagName) { createOptions._defaultTagName = _emberHtmlbarsHooksGetValue["default"](attrs._defaultTagName); } if (attrs.viewName) { createOptions.viewName = _emberHtmlbarsHooksGetValue["default"](attrs.viewName); } } ComponentNodeManager.prototype.render = function (_env, visitor) { var component = this.component; var attrs = this.attrs; return _emberHtmlbarsSystemInstrumentationSupport.instrument(component, function () { var env = _env.childWithView(component); 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; } _emberMetalCore["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 _htmlbarsUtilSafeString["default"](content)); } ComponentNodeManager.prototype.rerender = function (_env, attrs, visitor) { var component = this.component; return _emberHtmlbarsSystemInstrumentationSupport.instrument(component, function () { var env = _env.childWithView(component); var snapshot = takeSnapshot(attrs); if (component._renderNode.shouldReceiveAttrs) { env.renderer.componentUpdateAttrs(component, snapshot); if (!component._isAngleBracket) { _emberMetalSet_properties["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); }; ComponentNodeManager.prototype.destroy = function () { var component = this.component; // Clear component's render node. Normally this gets cleared // during view destruction, but in this case we're re-assigning the // node to a different view and it will get cleaned up automatically. component._renderNode = null; component.destroy(); }; function createComponent(_component, isAngleBracket, _props, renderNode, env) { var attrs = arguments.length <= 5 || arguments[5] === undefined ? {} : arguments[5]; var props = _emberMetalMerge.assign({}, _props); if (!isAngleBracket) { var hasSuppliedController = ("controller" in attrs); // 2.0TODO remove _emberMetalCore["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; } props.renderer = props.parentView ? props.parentView.renderer : env.container.lookup("renderer:-dom"); props._viewRegistry = props.parentView ? props.parentView._viewRegistry : env.container.lookup("-view-registry:main"); 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) { _emberMetalProperty_set.set(props.parentView, props.viewName, component); } } component._renderNode = renderNode; renderNode.emberView = component; renderNode.buildChildEnv = buildChildEnv; 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] = _emberHtmlbarsHooksGetCellOrValue["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") { _emberMetalCore["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[_emberViewsCompatAttrsProxy.MUTABLE_CELL]) { target[prop] = value.value; } else { target[prop] = value; } } return target; } function buildChildEnv(state, env) { return env.childWithView(this.emberView); } }); // In theory this should come through the env, but it should // be safe to import this until we make the hook system public // and it gets actively used in addons or other downstream // libraries. 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, _emberMetalMerge, _emberMetalCore, _emberViewsSystemBuildComponentTemplate, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalSet_properties, _emberViewsViewsView, _emberViewsCompatAttrsProxy, _emberHtmlbarsHooksGetCellOrValue, _emberHtmlbarsSystemInstrumentationSupport, _emberHtmlbarsNodeManagersComponentNodeManager, _emberHtmlbarsHooksGetValue) { 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) { _emberMetalCore["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 = _emberHtmlbarsHooksGetValue["default"](attrs.id); } if (attrs && attrs.tagName) { options.tagName = _emberHtmlbarsHooksGetValue["default"](attrs.tagName); } if (attrs && attrs._defaultTagName) { options._defaultTagName = _emberHtmlbarsHooksGetValue["default"](attrs._defaultTagName); } if (attrs && attrs.viewName) { options.viewName = _emberHtmlbarsHooksGetValue["default"](attrs.viewName); } if (found.component.create && contentScope && contentScope.self) { options._context = _emberHtmlbarsHooksGetValue["default"](contentScope.self); } if (found.self) { options._context = _emberHtmlbarsHooksGetValue["default"](found.self); } component = componentInfo.component = createOrUpdateComponent(found.component, options, found.createOptions, renderNode, env, attrs); var layout = _emberMetalProperty_get.get(component, "layout"); if (layout) { componentInfo.layout = layout; if (!contentTemplate) { var template = getTemplate(component); if (template) { _emberMetalCore["default"].deprecate("Using deprecated `template` property on a " + (component.isView ? "View" : "Component") + "."); contentTemplate = template.raw; } } } else { componentInfo.layout = getTemplate(component) || componentInfo.layout; } renderNode.emberView = component; } _emberMetalCore["default"].assert("BUG: ViewNodeManager.create can take a scope or a self, but not both", !(contentScope && found.self)); var results = _emberViewsSystemBuildComponentTemplate["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 _emberHtmlbarsSystemInstrumentationSupport.instrument(component, function () { var newEnv = env; if (component) { newEnv = env.childWithView(component); } if (component) { var snapshot = takeSnapshot(attrs); env.renderer.setAttrs(this.component, snapshot); 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; _emberHtmlbarsNodeManagersComponentNodeManager.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 _emberHtmlbarsSystemInstrumentationSupport.instrument(component, function () { var newEnv = env; if (component) { newEnv = env.childWithView(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); _emberMetalSet_properties["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); } return newEnv; }, this); }; ViewNodeManager.prototype.destroy = function () { if (this.component) { this.component.destroy(); this.component = null; } }; function getTemplate(componentOrView) { return componentOrView.isComponent ? _emberMetalProperty_get.get(componentOrView, "_template") : _emberMetalProperty_get.get(componentOrView, "template"); } function createOrUpdateComponent(component, options, createOptions, renderNode, env) { var attrs = arguments.length <= 5 || arguments[5] === undefined ? {} : arguments[5]; var snapshot = takeSnapshot(attrs); var props = _emberMetalMerge["default"]({}, options); var defaultController = _emberViewsViewsView["default"].proto().controller; var hasSuppliedController = "controller" in attrs || "controller" in props; if (!props.ownerView && options.parentView) { props.ownerView = options.parentView.ownerView; } props.attrs = snapshot; if (component.create) { var proto = component.proto(); if (createOptions) { _emberMetalMerge["default"](props, createOptions); } mergeBindings(props, shadowedAttrs(proto, snapshot)); props.container = options.parentView ? options.parentView.container : env.container; props.renderer = options.parentView ? options.parentView.renderer : props.container && props.container.lookup("renderer:-dom"); props._viewRegistry = options.parentView ? options.parentView._viewRegistry : props.container && props.container.lookup("-view-registry:main"); if (proto.controller !== defaultController || hasSuppliedController) { delete props._context; } component = component.create(props); } else { mergeBindings(props, shadowedAttrs(component, snapshot)); _emberMetalSet_properties["default"](component, props); } if (options.parentView) { options.parentView.appendChild(component); if (options.viewName) { _emberMetalProperty_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] = _emberHtmlbarsHooksGetCellOrValue["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") { _emberMetalCore["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[_emberViewsCompatAttrsProxy.MUTABLE_CELL]) { target[prop] = value.value; } else { target[prop] = value; } } return target; } }); // In theory this should come through the env, but it should // be safe to import this until we make the hook system public // and it gets actively used in addons or other downstream // libraries. enifed("ember-htmlbars/streams/built-in-helper", ["exports", "ember-metal/streams/stream", "ember-metal/platform/create", "ember-metal/merge", "ember-htmlbars/streams/utils"], function (exports, _emberMetalStreamsStream, _emberMetalPlatformCreate, _emberMetalMerge, _emberHtmlbarsStreamsUtils) { exports["default"] = BuiltInHelperStream; function BuiltInHelperStream(helper, params, hash, templates, env, scope, context, label) { this.init(label); this.helper = helper; this.params = params; this.templates = templates; this.env = env; this.scope = scope; this.hash = hash; this.context = context; } BuiltInHelperStream.prototype = _emberMetalPlatformCreate["default"](_emberMetalStreamsStream["default"].prototype); _emberMetalMerge["default"](BuiltInHelperStream.prototype, { compute: function () { // Using call and undefined is probably not needed, these are only internal return this.helper.call(this.context, _emberHtmlbarsStreamsUtils.getArrayValues(this.params), _emberHtmlbarsStreamsUtils.getHashValues(this.hash), this.templates, this.env, this.scope); } }); }); enifed("ember-htmlbars/streams/compat-helper", ["exports", "ember-metal/streams/stream", "ember-metal/platform/create", "ember-metal/merge"], function (exports, _emberMetalStreamsStream, _emberMetalPlatformCreate, _emberMetalMerge) { exports["default"] = CompatHelperStream; function CompatHelperStream(helper, params, hash, templates, env, scope, label) { this.init(label); this.helper = helper.helperFunction; this.params = params; this.templates = templates; this.env = env; this.scope = scope; this.hash = hash; } CompatHelperStream.prototype = _emberMetalPlatformCreate["default"](_emberMetalStreamsStream["default"].prototype); _emberMetalMerge["default"](CompatHelperStream.prototype, { compute: function () { // Using call and undefined is probably not needed, these are only internal return this.helper.call(undefined, this.params, this.hash, this.templates, this.env, this.scope); } }); }); enifed("ember-htmlbars/streams/helper-factory", ["exports", "ember-metal/streams/stream", "ember-metal/platform/create", "ember-metal/merge", "ember-htmlbars/streams/utils"], function (exports, _emberMetalStreamsStream, _emberMetalPlatformCreate, _emberMetalMerge, _emberHtmlbarsStreamsUtils) { exports["default"] = HelperFactoryStream; function HelperFactoryStream(helperFactory, params, hash, label) { this.init(label); this.helperFactory = helperFactory; this.params = params; this.hash = hash; this.linkable = true; this.helper = null; } HelperFactoryStream.prototype = _emberMetalPlatformCreate["default"](_emberMetalStreamsStream["default"].prototype); _emberMetalMerge["default"](HelperFactoryStream.prototype, { compute: function () { if (!this.helper) { this.helper = this.helperFactory.create({ _stream: this }); } return this.helper.compute(_emberHtmlbarsStreamsUtils.getArrayValues(this.params), _emberHtmlbarsStreamsUtils.getHashValues(this.hash)); }, deactivate: function () { this.super$deactivate(); if (this.helper) { this.helper.destroy(); this.helper = null; } }, super$deactivate: HelperFactoryStream.prototype.deactivate }); }); enifed("ember-htmlbars/streams/helper-instance", ["exports", "ember-metal/streams/stream", "ember-metal/platform/create", "ember-metal/merge", "ember-htmlbars/streams/utils"], function (exports, _emberMetalStreamsStream, _emberMetalPlatformCreate, _emberMetalMerge, _emberHtmlbarsStreamsUtils) { exports["default"] = HelperInstanceStream; function HelperInstanceStream(helper, params, hash, label) { this.init(label); this.helper = helper; this.params = params; this.hash = hash; this.linkable = true; } HelperInstanceStream.prototype = _emberMetalPlatformCreate["default"](_emberMetalStreamsStream["default"].prototype); _emberMetalMerge["default"](HelperInstanceStream.prototype, { compute: function () { return this.helper.compute(_emberHtmlbarsStreamsUtils.getArrayValues(this.params), _emberHtmlbarsStreamsUtils.getHashValues(this.hash)); } }); }); enifed("ember-htmlbars/streams/utils", ["exports", "ember-htmlbars/hooks/get-value"], function (exports, _emberHtmlbarsHooksGetValue) { exports.getArrayValues = getArrayValues; exports.getHashValues = getHashValues; // 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(_emberHtmlbarsHooksGetValue["default"](params[i])); } return out; } function getHashValues(hash) { var out = {}; for (var prop in hash) { out[prop] = _emberHtmlbarsHooksGetValue["default"](hash[prop]); } return out; } }); enifed("ember-htmlbars/system/append-templated-view", ["exports", "ember-metal/core", "ember-metal/property_get", "ember-views/views/view"], function (exports, _emberMetalCore, _emberMetalProperty_get, _emberViewsViewsView) { exports["default"] = appendTemplatedView; function appendTemplatedView(parentView, morph, viewClassOrInstance, props) { var viewProto; if (_emberViewsViewsView["default"].detectInstance(viewClassOrInstance)) { viewProto = viewClassOrInstance; } else { viewProto = viewClassOrInstance.proto(); } _emberMetalCore["default"].assert("You cannot provide a template block if you also specified a templateName", !props.template || !_emberMetalProperty_get.get(props, "templateName") && !_emberMetalProperty_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 = _emberMetalProperty_get.get(parentView, "context"); // TODO: is this right?! } props._morph = morph; return parentView.appendChild(viewClassOrInstance, props); } }); /** @module ember @submodule ember-htmlbars */ // Ember.assert 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, _emberMetalCore, _emberViewsComponent_lookup, _emberViewsSystemJquery, _emberMetalError, _emberRuntimeSystemLazy_load, _emberTemplateCompilerSystemCompile, _emberMetalEnvironment) { /** @module ember @submodule ember-htmlbars */ /** Find templates stored in the head tag as script tags and make them available to `Ember.CoreView` in the global `Ember.TEMPLATES` object. This will be run as as jQuery DOM-ready callback. Script tags with `text/x-handlebars` will be compiled with Ember's template compiler and are suitable for use as a view's template. Those with type `text/x-raw-handlebars` will be compiled with regular Handlebars and are suitable for use in views' computed properties. @private @method bootstrap @for Ember.HTMLBars @static @param ctx */ function bootstrap(ctx) { var selectors = "script[type=\"text/x-handlebars\"], script[type=\"text/x-raw-handlebars\"]"; _emberViewsSystemJquery["default"](selectors, ctx).each(function () { // Get a reference to the script tag var script = _emberViewsSystemJquery["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 = _emberViewsSystemJquery["default"].proxy(Handlebars.compile, Handlebars); template = compile(script.html()); } else { template = _emberTemplateCompilerSystemCompile["default"](script.html(), { moduleName: templateName }); } // Check if template of same name already exists if (_emberMetalCore["default"].TEMPLATES[templateName] !== undefined) { throw new _emberMetalError["default"]("Template named \"" + templateName + "\" already exists."); } // For templates which have a name, we save them and then remove them from the DOM _emberMetalCore["default"].TEMPLATES[templateName] = template; // Remove script tag from DOM script.remove(); }); } function _bootstrap() { bootstrap(_emberViewsSystemJquery["default"](document)); } function registerComponentLookup(app) { app.registry.register("component-lookup:main", _emberViewsComponent_lookup["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. */ _emberRuntimeSystemLazy_load.onLoad("Ember.Application", function (Application) { Application.initializer({ name: "domTemplates", initialize: _emberMetalEnvironment["default"].hasDOM ? _bootstrap : function () {} }); Application.instanceInitializer({ name: "registerComponentLookup", initialize: registerComponentLookup }); }); exports["default"] = bootstrap; }); /*globals Handlebars */ /** @module ember @submodule ember-htmlbars */ enifed('ember-htmlbars/system/discover-known-helpers', ['exports', 'ember-metal/core', 'ember-metal/dictionary', 'ember-metal/keys'], function (exports, _emberMetalCore, _emberMetalDictionary, _emberMetalKeys) { exports["default"] = discoverKnownHelpers; function discoverKnownHelpers(container) { var registry = container && container._registry; var helpers = _emberMetalDictionary["default"](null); if (_emberMetalCore["default"].FEATURES.isEnabled('ember-htmlbars-dashless-helpers')) { if (!registry) { return helpers; } var known = registry.knownForType('helper'); var knownContainerKeys = _emberMetalKeys["default"](known); for (var index = 0, _length = knownContainerKeys.length; index < _length; index++) { var fullName = knownContainerKeys[index]; var _name = fullName.slice(7); // remove `helper:` from fullName helpers[_name] = true; } } return helpers; } }); 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, _emberHtmlbarsMorphsMorph, _emberHtmlbarsMorphsAttrMorph, _emberMetalPlatformCreate) { function EmberDOMHelper(_document) { _domHelper["default"].call(this, _document); } var proto = EmberDOMHelper.prototype = _emberMetalPlatformCreate["default"](_domHelper["default"].prototype); proto.MorphClass = _emberHtmlbarsMorphsMorph["default"]; proto.AttrMorphClass = _emberHtmlbarsMorphsAttrMorph["default"]; exports["default"] = EmberDOMHelper; }); enifed("ember-htmlbars/system/helper", ["exports"], function (exports) { /** @module ember @submodule ember-templates */ 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, _emberMetalInstrumentation) { exports.instrument = instrument; /** Provides instrumentation for node managers. Wrap your node manager's render and re-render methods with this function. @param {Object} component Component or View instance (optional) @param {Function} callback The function to instrument @param {Object} context The context to call the function with @return {Object} Return value from the invoked callback @private */ function instrument(component, callback, context) { var instrumentName, val, details, end; // Only instrument if there's at least one subscriber. if (_emberMetalInstrumentation.subscribers.length) { if (component) { instrumentName = component.instrumentName; } else { instrumentName = 'node'; } details = {}; if (component) { component.instrumentDetails(details); } end = _emberMetalInstrumentation._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/invoke-helper", ["exports", "ember-htmlbars/streams/helper-instance", "ember-htmlbars/streams/helper-factory", "ember-htmlbars/streams/built-in-helper", "ember-htmlbars/streams/compat-helper"], function (exports, _emberHtmlbarsStreamsHelperInstance, _emberHtmlbarsStreamsHelperFactory, _emberHtmlbarsStreamsBuiltInHelper, _emberHtmlbarsStreamsCompatHelper) { exports.buildHelperStream = buildHelperStream; function buildHelperStream(helper, params, hash, templates, env, scope, context, label) { Ember.assert("Helpers may not be used in the block form, for example {{#my-helper}}{{/my-helper}}. Please use a component, or alternatively use the helper in combination with a built-in Ember helper, for example {{#if (my-helper)}}{{/if}}.", !helper.isHelperInstance || !helper.isHelperFactory && !templates.template.meta); if (helper.isHelperFactory) { return new _emberHtmlbarsStreamsHelperFactory["default"](helper, params, hash, label); } else if (helper.isHelperInstance) { return new _emberHtmlbarsStreamsHelperInstance["default"](helper, params, hash, label); } else if (helper.helperFunction) { return new _emberHtmlbarsStreamsCompatHelper["default"](helper, params, hash, templates, env, scope, label); } else { return new _emberHtmlbarsStreamsBuiltInHelper["default"](helper, params, hash, templates, env, scope, context, label); } } }); enifed("ember-htmlbars/system/lookup-helper", ["exports", "ember-metal/core", "ember-metal/cache", "ember-htmlbars/compat/helper"], function (exports, _emberMetalCore, _emberMetalCache, _emberHtmlbarsCompatHelper) { exports.validateLazyHelperName = validateLazyHelperName; exports.findHelper = findHelper; exports["default"] = lookupHelper; var CONTAINS_DASH_CACHE = new _emberMetalCache["default"](1000, function (key) { return key.indexOf("-") !== -1; }); exports.CONTAINS_DASH_CACHE = CONTAINS_DASH_CACHE; function validateLazyHelperName(helperName, container, keywords, knownHelpers) { if (!container || helperName in keywords) { return false; } if (knownHelpers[helperName] || CONTAINS_DASH_CACHE.get(helperName)) { return true; } } function isLegacyBareHelper(helper) { return helper && (!helper.isHelperFactory && !helper.isHelperInstance && !helper.isHTMLBars); } /** Used to lookup/resolve handlebars helpers. The lookup order is: * Look for a registered helper * If a dash exists in the name: * Look for a helper registed in the container * Use Ember.ComponentLookup to find an Ember.Component that resolves to the given name @private @method resolveHelper @param {String} name the name of the helper to lookup @return {Helper} */ function findHelper(name, view, env) { var helper = env.helpers[name]; if (!helper) { var container = env.container; if (validateLazyHelperName(name, container, env.hooks.keywords, env.knownHelpers)) { var helperName = "helper:" + name; if (container._registry.has(helperName)) { helper = container.lookupFactory(helperName); if (isLegacyBareHelper(helper)) { _emberMetalCore["default"].deprecate("The helper \"" + name + "\" is a deprecated bare function helper. Please use Ember.Helper.build to wrap helper functions."); helper = new _emberHtmlbarsCompatHelper["default"](helper); } } } } return helper; } function lookupHelper(name, view, env) { var helper = findHelper(name, view, env); _emberMetalCore["default"].assert("A helper named '" + name + "' could not be found", !!helper); return helper; } }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/system/make-view-helper", ["exports"], function (exports) { 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/helper"], function (exports, _emberHtmlbarsHelper) { exports["default"] = makeBoundHelper; /** Create a bound helper. Accepts a function that receives the ordered and hash parameters from the template. If a bound property was provided in the template it will be resolved to its value and any changes to the bound property cause the helper function to be re-run with the updated values. * `params` - An array of resolved ordered parameters. * `hash` - An object containing the hash parameters. For example: * With an unquoted ordered parameter: ```javascript {{x-capitalize foo}} ``` Assuming `foo` was set to `"bar"`, the bound helper would receive `["bar"]` as its first argument, and an empty hash as its second. * With a quoted ordered parameter: ```javascript {{x-capitalize "foo"}} ``` The bound helper would receive `["foo"]` as its first argument, and an empty hash as its second. * With an unquoted hash parameter: ```javascript {{x-repeat "foo" count=repeatCount}} ``` Assuming that `repeatCount` resolved to 2, the bound helper would receive `["foo"]` as its first argument, and { count: 2 } as its second. @private @method makeBoundHelper @for Ember.HTMLBars @param {Function} fn @since 1.10.0 */ function makeBoundHelper(fn) { return _emberHtmlbarsHelper.helper(fn); } }); /** @module ember @submodule ember-htmlbars */ enifed("ember-htmlbars/system/render-env", ["exports", "ember-htmlbars/env", "ember-htmlbars/system/discover-known-helpers"], function (exports, _emberHtmlbarsEnv, _emberHtmlbarsSystemDiscoverKnownHelpers) { exports["default"] = RenderEnv; function RenderEnv(options) { this.lifecycleHooks = options.lifecycleHooks || []; this.renderedViews = options.renderedViews || []; this.renderedNodes = options.renderedNodes || {}; this.hasParentOutlet = options.hasParentOutlet || false; this.view = options.view; this.outletState = options.outletState; this.container = options.container; this.renderer = options.renderer; this.dom = options.dom; this.knownHelpers = options.knownHelpers || _emberHtmlbarsSystemDiscoverKnownHelpers["default"](options.container); this.hooks = _emberHtmlbarsEnv["default"].hooks; this.helpers = _emberHtmlbarsEnv["default"].helpers; this.useFragmentCache = _emberHtmlbarsEnv["default"].useFragmentCache; } RenderEnv.build = function (view) { return new RenderEnv({ view: view, outletState: view.outletState, container: view.container, renderer: view.renderer, dom: view.renderer._dom }); }; RenderEnv.prototype.childWithView = function (view) { return new RenderEnv({ view: view, outletState: this.outletState, container: this.container, renderer: this.renderer, dom: this.dom, lifecycleHooks: this.lifecycleHooks, renderedViews: this.renderedViews, renderedNodes: this.renderedNodes, hasParentOutlet: this.hasParentOutlet, knownHelpers: this.knownHelpers }); }; RenderEnv.prototype.childWithOutletState = function (outletState) { var hasParentOutlet = arguments.length <= 1 || arguments[1] === undefined ? this.hasParentOutlet : arguments[1]; return new RenderEnv({ view: this.view, outletState: outletState, container: this.container, renderer: this.renderer, dom: this.dom, lifecycleHooks: this.lifecycleHooks, renderedViews: this.renderedViews, renderedNodes: this.renderedNodes, hasParentOutlet: hasParentOutlet, knownHelpers: this.knownHelpers }); }; }); enifed("ember-htmlbars/system/render-view", ["exports", "ember-htmlbars/node-managers/view-node-manager", "ember-htmlbars/system/render-env"], function (exports, _emberHtmlbarsNodeManagersViewNodeManager, _emberHtmlbarsSystemRenderEnv) { exports.renderHTMLBarsBlock = renderHTMLBarsBlock; // This function only gets called once per render of a "root view" (`appendTo`). Otherwise, // HTMLBars propagates the existing env and renders templates for a given render node. function renderHTMLBarsBlock(view, block, renderNode) { var env = _emberHtmlbarsSystemRenderEnv["default"].build(view); view.env = env; _emberHtmlbarsNodeManagersViewNodeManager.createOrUpdateComponent(view, {}, null, renderNode, env); var nodeManager = new _emberHtmlbarsNodeManagersViewNodeManager["default"](view, null, renderNode, block, view.tagName !== ""); nodeManager.render(env, {}); } }); enifed("ember-htmlbars/templates/component", ["exports", "ember-template-compiler/system/template"], function (exports, _emberTemplateCompilerSystemTemplate) { exports["default"] = _emberTemplateCompilerSystemTemplate["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", ["loc", [null, [1, 0], [1, 9]]]]], locals: [], templates: [] }; })()); }); enifed("ember-htmlbars/templates/container-view", ["exports", "ember-template-compiler/system/template"], function (exports, _emberTemplateCompilerSystemTemplate) { exports["default"] = _emberTemplateCompilerSystemTemplate["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", ["loc", [null, [1, 63], [1, 72]]]]], [], ["loc", [null, [1, 56], [1, 74]]]]], 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", ["loc", [null, [1, 108], [1, 123]]]]], ["_defaultTagName", ["get", "view._emptyViewTagName", ["loc", [null, [1, 140], [1, 162]]]]], ["loc", [null, [1, 101], [1, 164]]]]], 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", ["loc", [null, [1, 84], [1, 99]]]]], [], 0, null, ["loc", [null, [1, 74], [1, 164]]]]], 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", ["loc", [null, [1, 8], [1, 23]]]]], ["key", "elementId"], 0, 1, ["loc", [null, [1, 0], [1, 173]]]]], locals: [], templates: [child0, child1] }; })()); }); enifed("ember-htmlbars/templates/empty", ["exports", "ember-template-compiler/system/template"], function (exports, _emberTemplateCompilerSystemTemplate) { exports["default"] = _emberTemplateCompilerSystemTemplate["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, _emberTemplateCompilerSystemTemplate) { exports["default"] = _emberTemplateCompilerSystemTemplate["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", ["loc", [null, [5, 24], [5, 28]]]]], [], ["loc", [null, [5, 8], [5, 31]]]]], 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", ["loc", [null, [4, 15], [4, 34]]]]], ["_defaultTagName", ["get", "view._itemTagName", ["loc", [null, [4, 51], [4, 68]]]]], 0, null, ["loc", [null, [4, 6], [6, 17]]]]], 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", ["loc", [null, [8, 22], [8, 26]]]]], [], ["loc", [null, [8, 6], [8, 29]]]]], 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", ["loc", [null, [3, 11], [3, 30]]]]], [], 0, 1, ["loc", [null, [3, 4], [9, 13]]]]], 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", ["loc", [null, [13, 24], [13, 28]]]]], [], ["loc", [null, [13, 8], [13, 31]]]]], 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", ["loc", [null, [12, 15], [12, 34]]]]], ["controller", ["get", "item", ["loc", [null, [12, 46], [12, 50]]]], "_defaultTagName", ["get", "view._itemTagName", ["loc", [null, [12, 67], [12, 84]]]]], 0, null, ["loc", [null, [12, 6], [14, 17]]]]], 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", ["loc", [null, [16, 22], [16, 26]]]]], ["controller", ["get", "item", ["loc", [null, [16, 38], [16, 42]]]]], ["loc", [null, [16, 6], [16, 45]]]]], 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", ["loc", [null, [11, 11], [11, 30]]]]], [], 0, 1, ["loc", [null, [11, 4], [17, 13]]]]], 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", "view.keyword", ["loc", [null, [2, 9], [2, 21]]]]], [], 0, 1, ["loc", [null, [2, 2], [18, 11]]]]], 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", ["loc", [null, [20, 10], [20, 25]]]]], ["_defaultTagName", ["get", "view._itemTagName", ["loc", [null, [20, 42], [20, 59]]]]], ["loc", [null, [20, 2], [20, 62]]]]], 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", ["loc", [null, [19, 11], [19, 26]]]]], [], 0, null, ["loc", [null, [19, 0], [21, 0]]]]], 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", ["loc", [null, [1, 9], [1, 30]]]]], ["-legacy-keyword", ["get", "view.keyword", ["loc", [null, [1, 47], [1, 59]]]]], 0, 1, ["loc", [null, [1, 0], [21, 11]]]]], locals: [], templates: [child0, child1] }; })()); }); enifed("ember-htmlbars/templates/link-to-escaped", ["exports", "ember-template-compiler/system/template"], function (exports, _emberTemplateCompilerSystemTemplate) { exports["default"] = _emberTemplateCompilerSystemTemplate["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", ["loc", [null, [1, 0], [1, 13]]]]], locals: [], templates: [] }; })()); }); enifed("ember-htmlbars/templates/link-to-unescaped", ["exports", "ember-template-compiler/system/template"], function (exports, _emberTemplateCompilerSystemTemplate) { exports["default"] = _emberTemplateCompilerSystemTemplate["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", ["loc", [null, [1, 0], [1, 15]]]]], locals: [], templates: [] }; })()); }); enifed("ember-htmlbars/templates/link-to", ["exports", "ember-template-compiler/system/template"], function (exports, _emberTemplateCompilerSystemTemplate) { exports["default"] = _emberTemplateCompilerSystemTemplate["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", ["loc", [null, [1, 38], [1, 51]]]]], 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", ["loc", [null, [1, 59], [1, 74]]]]], 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", ["loc", [null, [1, 23], [1, 36]]]]], [], 0, 1, ["loc", [null, [1, 17], [1, 81]]]]], 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", ["loc", [null, [1, 89], [1, 98]]]]], 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", ["loc", [null, [1, 6], [1, 15]]]]], [], 0, 1, ["loc", [null, [1, 0], [1, 105]]]]], locals: [], templates: [child0, child1] }; })()); }); enifed("ember-htmlbars/templates/select-optgroup", ["exports", "ember-template-compiler/system/template"], function (exports, _emberTemplateCompilerSystemTemplate) { exports["default"] = _emberTemplateCompilerSystemTemplate["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", ["loc", [null, [1, 40], [1, 56]]]]], ["content", ["get", "item", ["loc", [null, [1, 65], [1, 69]]]], "selection", ["get", "attrs.selection", ["loc", [null, [1, 80], [1, 95]]]], "parentValue", ["get", "attrs.value", ["loc", [null, [1, 108], [1, 119]]]], "multiple", ["get", "attrs.multiple", ["loc", [null, [1, 129], [1, 143]]]], "optionLabelPath", ["get", "attrs.optionLabelPath", ["loc", [null, [1, 160], [1, 181]]]], "optionValuePath", ["get", "attrs.optionValuePath", ["loc", [null, [1, 198], [1, 219]]]]], ["loc", [null, [1, 33], [1, 221]]]]], 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", ["loc", [null, [1, 8], [1, 21]]]]], [], 0, null, ["loc", [null, [1, 0], [1, 230]]]]], locals: [], templates: [child0] }; })()); }); enifed("ember-htmlbars/templates/select-option", ["exports", "ember-template-compiler/system/template"], function (exports, _emberTemplateCompilerSystemTemplate) { exports["default"] = _emberTemplateCompilerSystemTemplate["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", ["loc", [null, [1, 0], [1, 16]]]]], locals: [], templates: [] }; })()); }); enifed("ember-htmlbars/templates/select", ["exports", "ember-template-compiler/system/template"], function (exports, _emberTemplateCompilerSystemTemplate) { exports["default"] = _emberTemplateCompilerSystemTemplate["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", ["loc", [null, [1, 36], [1, 51]]]]], 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", ["loc", [null, [1, 142], [1, 156]]]]], ["content", ["get", "group.content", ["loc", [null, [1, 165], [1, 178]]]], "label", ["get", "group.label", ["loc", [null, [1, 185], [1, 196]]]], "selection", ["get", "view.selection", ["loc", [null, [1, 207], [1, 221]]]], "value", ["get", "view.value", ["loc", [null, [1, 228], [1, 238]]]], "multiple", ["get", "view.multiple", ["loc", [null, [1, 248], [1, 261]]]], "optionLabelPath", ["get", "view.optionLabelPath", ["loc", [null, [1, 278], [1, 298]]]], "optionValuePath", ["get", "view.optionValuePath", ["loc", [null, [1, 315], [1, 335]]]], "optionView", ["get", "view.optionView", ["loc", [null, [1, 347], [1, 362]]]]], ["loc", [null, [1, 135], [1, 364]]]]], 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", ["loc", [null, [1, 103], [1, 122]]]]], [], 0, null, ["loc", [null, [1, 95], [1, 373]]]]], 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", ["loc", [null, [1, 420], [1, 435]]]]], ["content", ["get", "item", ["loc", [null, [1, 444], [1, 448]]]], "selection", ["get", "view.selection", ["loc", [null, [1, 459], [1, 473]]]], "parentValue", ["get", "view.value", ["loc", [null, [1, 486], [1, 496]]]], "multiple", ["get", "view.multiple", ["loc", [null, [1, 506], [1, 519]]]], "optionLabelPath", ["get", "view.optionLabelPath", ["loc", [null, [1, 536], [1, 556]]]], "optionValuePath", ["get", "view.optionValuePath", ["loc", [null, [1, 573], [1, 593]]]]], ["loc", [null, [1, 413], [1, 595]]]]], 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", ["loc", [null, [1, 389], [1, 401]]]]], [], 0, null, ["loc", [null, [1, 381], [1, 604]]]]], 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", ["loc", [null, [1, 6], [1, 17]]]]], [], 0, null, ["loc", [null, [1, 0], [1, 67]]]], ["block", "if", [["get", "view.optionGroupPath", ["loc", [null, [1, 73], [1, 93]]]]], [], 1, 2, ["loc", [null, [1, 67], [1, 611]]]]], locals: [], templates: [child0, child1, child2] }; })()); }); enifed("ember-htmlbars/templates/top-level-view", ["exports", "ember-template-compiler/system/template"], function (exports, _emberTemplateCompilerSystemTemplate) { exports["default"] = _emberTemplateCompilerSystemTemplate["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", ["loc", [null, [1, 0], [1, 10]]]]], locals: [], templates: [] }; })()); }); enifed("ember-htmlbars/utils/decode-each-key", ["exports", "ember-metal/core", "ember-metal/property_get", "ember-metal/utils"], function (exports, _emberMetalCore, _emberMetalProperty_get, _emberMetalUtils) { exports["default"] = decodeEachKey; function identity(item) { var key = undefined; var type = typeof item; if (type === "string" || type === "number") { key = item; } else { key = _emberMetalUtils.guidFor(item); } return key; } function decodeEachKey(item, keyPath, index) { var key, deprecatedSpecialKey; switch (keyPath) { case "@index": key = index; break; case "@guid": deprecatedSpecialKey = "@guid"; key = _emberMetalUtils.guidFor(item); break; case "@item": deprecatedSpecialKey = "@item"; key = item; break; case "@identity": key = identity(item); break; default: if (keyPath) { key = _emberMetalProperty_get.get(item, keyPath); } else { key = identity(item); } } if (typeof key === "number") { key = String(key); } _emberMetalCore["default"].deprecate("Using '" + deprecatedSpecialKey + "' with the {{each}} helper, is deprecated. Switch to '@identity' or remove 'key=' from your template.", !deprecatedSpecialKey); return key; } }); enifed('ember-htmlbars/utils/is-component', ['exports', 'ember-htmlbars/system/lookup-helper'], function (exports, _emberHtmlbarsSystemLookupHelper) { exports["default"] = isComponent; /* Given a path name, returns whether or not a component with that name was found in the container. */ function isComponent(env, scope, path) { var container = env.container; if (!container) { return false; } if (!_emberHtmlbarsSystemLookupHelper.CONTAINS_DASH_CACHE.get(path)) { return false; } return container._registry.has('component:' + path) || container._registry.has('template:components/' + path); } }); /** @module ember @submodule ember-htmlbars */ enifed('ember-htmlbars/utils/lookup-component', ['exports'], function (exports) { 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) { 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, _htmlbarsUtil, _emberRuntimeSystemString) { /** Mark a string as safe for unescaped output with Ember templates. If you return HTML from a helper, use this function to ensure Ember's rendering layer does not escape the HTML. ```javascript Ember.String.htmlSafe('
    someString
    ') ``` @method htmlSafe @for Ember.String @static @return {Handlebars.SafeString} a string that will not be html escaped by Handlebars @public */ function htmlSafe(str) { if (str === null || str === undefined) { return ""; } if (typeof str !== "string") { str = "" + str; } return new _htmlbarsUtil.SafeString(str); } _emberRuntimeSystemString["default"].htmlSafe = htmlSafe; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { String.prototype.htmlSafe = function () { return htmlSafe(this); }; } exports.SafeString = _htmlbarsUtil.SafeString; exports.htmlSafe = htmlSafe; exports.escapeExpression = _htmlbarsUtil.escapeExpression; }); /** @module ember @submodule ember-htmlbars */ // required so we can extend this object. enifed("ember-htmlbars/utils/subscribe", ["exports", "ember-metal/streams/utils"], function (exports, _emberMetalStreamsUtils) { exports["default"] = subscribe; function subscribe(node, env, scope, stream) { if (!_emberMetalStreamsUtils.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, _emberMetalStreamsUtils.labelFor(stream)); })); } }); enifed("ember-htmlbars/utils/update-scope", ["exports", "ember-metal/streams/proxy-stream", "ember-htmlbars/utils/subscribe"], function (exports, _emberMetalStreamsProxyStream, _emberHtmlbarsUtilsSubscribe) { exports["default"] = updateScope; function updateScope(scope, key, newValue, renderNode, isSelf) { var existing = scope[key]; if (existing) { existing.setSource(newValue); } else { var stream = new _emberMetalStreamsProxyStream["default"](newValue, isSelf ? null : key); if (renderNode) { _emberHtmlbarsUtilsSubscribe["default"](renderNode, scope, stream); } scope[key] = stream; } } }); enifed('ember-metal-views', ['exports', 'ember-metal-views/renderer'], function (exports, _emberMetalViewsRenderer) { exports.Renderer = _emberMetalViewsRenderer["default"]; }); enifed("ember-metal-views/renderer", ["exports", "ember-metal/run_loop", "ember-metal/property_get", "ember-metal/property_set", "ember-metal/merge", "ember-metal/set_properties", "ember-views/system/build-component-template", "ember-metal/enumerable_utils"], function (exports, _emberMetalRun_loop, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalMerge, _emberMetalSet_properties, _emberViewsSystemBuildComponentTemplate, _emberMetalEnumerable_utils) { //import { deprecation } from "ember-views/compat/attrs-proxy"; 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 = _emberMetalProperty_get.get(view, "layout"); var template = view.isComponent ? _emberMetalProperty_get.get(view, "_template") : _emberMetalProperty_get.get(view, "template"); var componentInfo = { component: view, layout: layout }; var block = _emberViewsSystemBuildComponentTemplate["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 && _emberMetalEnumerable_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; _emberMetalRun_loop["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; _emberMetalRun_loop["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); }; 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) { _emberMetalProperty_set.set(view, "attrs", attrs); }; // set attrs the first time Renderer.prototype.componentInitAttrs = function (component, attrs) { _emberMetalProperty_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) { this.setAttrs(view, attrs); }; // setting new attrs Renderer.prototype.componentUpdateAttrs = function (component, newAttrs) { var oldAttrs = null; if (component.attrs) { oldAttrs = _emberMetalMerge.assign({}, component.attrs); _emberMetalSet_properties["default"](component.attrs, newAttrs); } else { _emberMetalProperty_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; _emberMetalRun_loop["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.element && view.element.parentNode) { 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"); } if (view._transitionTo) { view._transitionTo("destroying"); } }; 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"); } if (view.trigger) { view.trigger("didDestroyElement"); } }; // element destroyed so view.destroy shouldn't try to remove it removedFromDOM exports["default"] = Renderer; }); /*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, _emberMetalCore, _emberMetalMerge, _emberMetalInstrumentation, _emberMetalUtils, _emberMetalError, _emberMetalEnumerable_utils, _emberMetalCache, _emberMetalPlatformDefine_property, _emberMetalPlatformCreate, _emberMetalArray, _emberMetalLogger, _emberMetalProperty_get, _emberMetalEvents, _emberMetalObserver_set, _emberMetalProperty_events, _emberMetalProperties, _emberMetalProperty_set, _emberMetalMap, _emberMetalGet_properties, _emberMetalSet_properties, _emberMetalWatch_key, _emberMetalChains, _emberMetalWatch_path, _emberMetalWatching, _emberMetalExpand_properties, _emberMetalComputed, _emberMetalAlias, _emberMetalComputed_macros, _emberMetalObserver, _emberMetalMixin, _emberMetalBinding, _emberMetalRun_loop, _emberMetalLibraries, _emberMetalIs_none, _emberMetalIs_empty, _emberMetalIs_blank, _emberMetalIs_present, _emberMetalKeys, _backburner, _emberMetalStreamsUtils, _emberMetalStreamsStream) { _emberMetalComputed.computed.empty = _emberMetalComputed_macros.empty; _emberMetalComputed.computed.notEmpty = _emberMetalComputed_macros.notEmpty; _emberMetalComputed.computed.none = _emberMetalComputed_macros.none; _emberMetalComputed.computed.not = _emberMetalComputed_macros.not; _emberMetalComputed.computed.bool = _emberMetalComputed_macros.bool; _emberMetalComputed.computed.match = _emberMetalComputed_macros.match; _emberMetalComputed.computed.equal = _emberMetalComputed_macros.equal; _emberMetalComputed.computed.gt = _emberMetalComputed_macros.gt; _emberMetalComputed.computed.gte = _emberMetalComputed_macros.gte; _emberMetalComputed.computed.lt = _emberMetalComputed_macros.lt; _emberMetalComputed.computed.lte = _emberMetalComputed_macros.lte; _emberMetalComputed.computed.alias = _emberMetalAlias["default"]; _emberMetalComputed.computed.oneWay = _emberMetalComputed_macros.oneWay; _emberMetalComputed.computed.reads = _emberMetalComputed_macros.oneWay; _emberMetalComputed.computed.readOnly = _emberMetalComputed_macros.readOnly; _emberMetalComputed.computed.defaultTo = _emberMetalComputed_macros.defaultTo; _emberMetalComputed.computed.deprecatingAlias = _emberMetalComputed_macros.deprecatingAlias; _emberMetalComputed.computed.and = _emberMetalComputed_macros.and; _emberMetalComputed.computed.or = _emberMetalComputed_macros.or; _emberMetalComputed.computed.any = _emberMetalComputed_macros.any; _emberMetalComputed.computed.collect = _emberMetalComputed_macros.collect; // END IMPORTS // BEGIN EXPORTS var EmberInstrumentation = _emberMetalCore["default"].Instrumentation = {}; EmberInstrumentation.instrument = _emberMetalInstrumentation.instrument; EmberInstrumentation.subscribe = _emberMetalInstrumentation.subscribe; EmberInstrumentation.unsubscribe = _emberMetalInstrumentation.unsubscribe; EmberInstrumentation.reset = _emberMetalInstrumentation.reset; _emberMetalCore["default"].instrument = _emberMetalInstrumentation.instrument; _emberMetalCore["default"].subscribe = _emberMetalInstrumentation.subscribe; _emberMetalCore["default"]._Cache = _emberMetalCache["default"]; _emberMetalCore["default"].generateGuid = _emberMetalUtils.generateGuid; _emberMetalCore["default"].GUID_KEY = _emberMetalUtils.GUID_KEY; _emberMetalCore["default"].platform = { defineProperty: _emberMetalProperties.defineProperty, hasPropertyAccessors: _emberMetalPlatformDefine_property.hasPropertyAccessors }; var EmberArrayPolyfills = _emberMetalCore["default"].ArrayPolyfills = {}; EmberArrayPolyfills.map = _emberMetalArray.map; EmberArrayPolyfills.forEach = _emberMetalArray.forEach; EmberArrayPolyfills.filter = _emberMetalArray.filter; EmberArrayPolyfills.indexOf = _emberMetalArray.indexOf; _emberMetalCore["default"].Error = _emberMetalError["default"]; _emberMetalCore["default"].guidFor = _emberMetalUtils.guidFor; _emberMetalCore["default"].META_DESC = _emberMetalUtils.META_DESC; _emberMetalCore["default"].EMPTY_META = _emberMetalUtils.EMPTY_META; _emberMetalCore["default"].meta = _emberMetalUtils.meta; _emberMetalCore["default"].getMeta = _emberMetalUtils.getMeta; _emberMetalCore["default"].setMeta = _emberMetalUtils.setMeta; _emberMetalCore["default"].metaPath = _emberMetalUtils.metaPath; _emberMetalCore["default"].inspect = _emberMetalUtils.inspect; _emberMetalCore["default"].tryCatchFinally = _emberMetalUtils.deprecatedTryCatchFinally; _emberMetalCore["default"].makeArray = _emberMetalUtils.makeArray; _emberMetalCore["default"].canInvoke = _emberMetalUtils.canInvoke; _emberMetalCore["default"].tryInvoke = _emberMetalUtils.tryInvoke; _emberMetalCore["default"].tryFinally = _emberMetalUtils.deprecatedTryFinally; _emberMetalCore["default"].wrap = _emberMetalUtils.wrap; _emberMetalCore["default"].apply = _emberMetalUtils.apply; _emberMetalCore["default"].applyStr = _emberMetalUtils.applyStr; _emberMetalCore["default"].uuid = _emberMetalUtils.uuid; _emberMetalCore["default"].Logger = _emberMetalLogger["default"]; _emberMetalCore["default"].get = _emberMetalProperty_get.get; _emberMetalCore["default"].getWithDefault = _emberMetalProperty_get.getWithDefault; _emberMetalCore["default"].normalizeTuple = _emberMetalProperty_get.normalizeTuple; _emberMetalCore["default"]._getPath = _emberMetalProperty_get._getPath; _emberMetalCore["default"].EnumerableUtils = _emberMetalEnumerable_utils["default"]; _emberMetalCore["default"].on = _emberMetalEvents.on; _emberMetalCore["default"].addListener = _emberMetalEvents.addListener; _emberMetalCore["default"].removeListener = _emberMetalEvents.removeListener; _emberMetalCore["default"]._suspendListener = _emberMetalEvents.suspendListener; _emberMetalCore["default"]._suspendListeners = _emberMetalEvents.suspendListeners; _emberMetalCore["default"].sendEvent = _emberMetalEvents.sendEvent; _emberMetalCore["default"].hasListeners = _emberMetalEvents.hasListeners; _emberMetalCore["default"].watchedEvents = _emberMetalEvents.watchedEvents; _emberMetalCore["default"].listenersFor = _emberMetalEvents.listenersFor; _emberMetalCore["default"].accumulateListeners = _emberMetalEvents.accumulateListeners; _emberMetalCore["default"]._ObserverSet = _emberMetalObserver_set["default"]; _emberMetalCore["default"].propertyWillChange = _emberMetalProperty_events.propertyWillChange; _emberMetalCore["default"].propertyDidChange = _emberMetalProperty_events.propertyDidChange; _emberMetalCore["default"].overrideChains = _emberMetalProperty_events.overrideChains; _emberMetalCore["default"].beginPropertyChanges = _emberMetalProperty_events.beginPropertyChanges; _emberMetalCore["default"].endPropertyChanges = _emberMetalProperty_events.endPropertyChanges; _emberMetalCore["default"].changeProperties = _emberMetalProperty_events.changeProperties; _emberMetalCore["default"].defineProperty = _emberMetalProperties.defineProperty; _emberMetalCore["default"].set = _emberMetalProperty_set.set; _emberMetalCore["default"].trySet = _emberMetalProperty_set.trySet; _emberMetalCore["default"].OrderedSet = _emberMetalMap.OrderedSet; _emberMetalCore["default"].Map = _emberMetalMap.Map; _emberMetalCore["default"].MapWithDefault = _emberMetalMap.MapWithDefault; _emberMetalCore["default"].getProperties = _emberMetalGet_properties["default"]; _emberMetalCore["default"].setProperties = _emberMetalSet_properties["default"]; _emberMetalCore["default"].watchKey = _emberMetalWatch_key.watchKey; _emberMetalCore["default"].unwatchKey = _emberMetalWatch_key.unwatchKey; _emberMetalCore["default"].flushPendingChains = _emberMetalChains.flushPendingChains; _emberMetalCore["default"].removeChainWatcher = _emberMetalChains.removeChainWatcher; _emberMetalCore["default"]._ChainNode = _emberMetalChains.ChainNode; _emberMetalCore["default"].finishChains = _emberMetalChains.finishChains; _emberMetalCore["default"].watchPath = _emberMetalWatch_path.watchPath; _emberMetalCore["default"].unwatchPath = _emberMetalWatch_path.unwatchPath; _emberMetalCore["default"].watch = _emberMetalWatching.watch; _emberMetalCore["default"].isWatching = _emberMetalWatching.isWatching; _emberMetalCore["default"].unwatch = _emberMetalWatching.unwatch; _emberMetalCore["default"].rewatch = _emberMetalWatching.rewatch; _emberMetalCore["default"].destroy = _emberMetalWatching.destroy; _emberMetalCore["default"].expandProperties = _emberMetalExpand_properties["default"]; _emberMetalCore["default"].ComputedProperty = _emberMetalComputed.ComputedProperty; _emberMetalCore["default"].computed = _emberMetalComputed.computed; _emberMetalCore["default"].cacheFor = _emberMetalComputed.cacheFor; _emberMetalCore["default"].addObserver = _emberMetalObserver.addObserver; _emberMetalCore["default"].observersFor = _emberMetalObserver.observersFor; _emberMetalCore["default"].removeObserver = _emberMetalObserver.removeObserver; _emberMetalCore["default"].addBeforeObserver = _emberMetalCore["default"].deprecateFunc("Ember.addBeforeObserver is deprecated and will be removed in the near future.", { url: "http://emberjs.com/deprecations/v1.x/#toc_beforeobserver" }, _emberMetalObserver._addBeforeObserver); _emberMetalCore["default"]._suspendBeforeObserver = _emberMetalObserver._suspendBeforeObserver; _emberMetalCore["default"]._suspendBeforeObservers = _emberMetalObserver._suspendBeforeObservers; _emberMetalCore["default"]._suspendObserver = _emberMetalObserver._suspendObserver; _emberMetalCore["default"]._suspendObservers = _emberMetalObserver._suspendObservers; _emberMetalCore["default"].beforeObserversFor = _emberMetalCore["default"].deprecateFunc("Ember.beforeObserversFor is deprecated and will be removed in the near future.", { url: "http://emberjs.com/deprecations/v1.x/#toc_beforeobserver" }, _emberMetalObserver._beforeObserversFor); _emberMetalCore["default"].removeBeforeObserver = _emberMetalCore["default"].deprecateFunc("Ember.removeBeforeObserver is deprecated and will be removed in the near future.", { url: "http://emberjs.com/deprecations/v1.x/#toc_beforeobserver" }, _emberMetalObserver._removeBeforeObserver); _emberMetalCore["default"].IS_BINDING = _emberMetalMixin.IS_BINDING; _emberMetalCore["default"].required = _emberMetalMixin.required; _emberMetalCore["default"].aliasMethod = _emberMetalMixin.aliasMethod; _emberMetalCore["default"].observer = _emberMetalMixin.observer; _emberMetalCore["default"].immediateObserver = _emberMetalMixin._immediateObserver; _emberMetalCore["default"].beforeObserver = _emberMetalCore["default"].deprecateFunc("Ember.beforeObserver is deprecated and will be removed in the near future.", { url: "http://emberjs.com/deprecations/v1.x/#toc_beforeobserver" }, _emberMetalMixin._beforeObserver); _emberMetalCore["default"].mixin = _emberMetalMixin.mixin; _emberMetalCore["default"].Mixin = _emberMetalMixin.Mixin; _emberMetalCore["default"].oneWay = _emberMetalBinding.oneWay; _emberMetalCore["default"].bind = _emberMetalBinding.bind; _emberMetalCore["default"].Binding = _emberMetalBinding.Binding; _emberMetalCore["default"].isGlobalPath = _emberMetalBinding.isGlobalPath; _emberMetalCore["default"].run = _emberMetalRun_loop["default"]; /** @class Backburner @for Ember @private */ _emberMetalCore["default"].Backburner = _backburner["default"]; // this is the new go forward, once Ember Data updates to using `_Backburner` we // can remove the non-underscored version. _emberMetalCore["default"]._Backburner = _backburner["default"]; _emberMetalCore["default"].libraries = new _emberMetalLibraries["default"](); _emberMetalCore["default"].libraries.registerCoreLibrary("Ember", _emberMetalCore["default"].VERSION); _emberMetalCore["default"].isNone = _emberMetalIs_none["default"]; _emberMetalCore["default"].isEmpty = _emberMetalIs_empty["default"]; _emberMetalCore["default"].isBlank = _emberMetalIs_blank["default"]; _emberMetalCore["default"].isPresent = _emberMetalIs_present["default"]; _emberMetalCore["default"].merge = _emberMetalMerge["default"]; if (_emberMetalCore["default"].FEATURES.isEnabled("ember-metal-stream")) { _emberMetalCore["default"].stream = { Stream: _emberMetalStreamsStream["default"], isStream: _emberMetalStreamsUtils.isStream, subscribe: _emberMetalStreamsUtils.subscribe, unsubscribe: _emberMetalStreamsUtils.unsubscribe, read: _emberMetalStreamsUtils.read, readHash: _emberMetalStreamsUtils.readHash, readArray: _emberMetalStreamsUtils.readArray, scanArray: _emberMetalStreamsUtils.scanArray, scanHash: _emberMetalStreamsUtils.scanHash, concat: _emberMetalStreamsUtils.concat, chain: _emberMetalStreamsUtils.chain }; } /** 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 @public */ _emberMetalCore["default"].onerror = null; // END EXPORTS // do this for side-effects of updating Ember.assert, warn, etc when // ember-debug is present if (_emberMetalCore["default"].__loader.registry["ember-debug"]) { requireModule("ember-debug"); } _emberMetalCore["default"].create = _emberMetalCore["default"].deprecateFunc("Ember.create is deprecated in favor of Object.create", _emberMetalPlatformCreate["default"]); _emberMetalCore["default"].keys = _emberMetalCore["default"].deprecateFunc("Ember.keys is deprecated in favor of Object.keys", _emberMetalKeys["default"]); exports["default"] = _emberMetalCore["default"]; }); /** @module ember @submodule ember-metal */ // BEGIN IMPORTS 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, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalCore, _emberMetalError, _emberMetalProperties, _emberMetalComputed, _emberMetalPlatformCreate, _emberMetalUtils, _emberMetalDependent_keys) { exports["default"] = alias; exports.AliasedProperty = AliasedProperty; function alias(altKey) { return new AliasedProperty(altKey); } function AliasedProperty(altKey) { this.isDescriptor = true; this.altKey = altKey; this._dependentKeys = [altKey]; } AliasedProperty.prototype = _emberMetalPlatformCreate["default"](_emberMetalProperties.Descriptor.prototype); AliasedProperty.prototype.get = function AliasedProperty_get(obj, keyName) { return _emberMetalProperty_get.get(obj, this.altKey); }; AliasedProperty.prototype.set = function AliasedProperty_set(obj, keyName, value) { return _emberMetalProperty_set.set(obj, this.altKey, value); }; AliasedProperty.prototype.willWatch = function (obj, keyName) { _emberMetalDependent_keys.addDependentKeys(this, obj, keyName, _emberMetalUtils.meta(obj)); }; AliasedProperty.prototype.didUnwatch = function (obj, keyName) { _emberMetalDependent_keys.removeDependentKeys(this, obj, keyName, _emberMetalUtils.meta(obj)); }; AliasedProperty.prototype.setup = function (obj, keyName) { _emberMetalCore["default"].assert("Setting alias '" + keyName + "' on self", this.altKey !== keyName); var m = _emberMetalUtils.meta(obj); if (m.watching[keyName]) { _emberMetalDependent_keys.addDependentKeys(this, obj, keyName, m); } }; AliasedProperty.prototype.teardown = function (obj, keyName) { var m = _emberMetalUtils.meta(obj); if (m.watching[keyName]) { _emberMetalDependent_keys.removeDependentKeys(this, obj, keyName, m); } }; AliasedProperty.prototype.readOnly = function () { this.set = AliasedProperty_readOnlySet; return this; }; function AliasedProperty_readOnlySet(obj, keyName, value) { throw new _emberMetalError["default"]("Cannot set read-only property '" + keyName + "' on object: " + _emberMetalUtils.inspect(obj)); } AliasedProperty.prototype.oneWay = function () { this.set = AliasedProperty_oneWaySet; return this; }; function AliasedProperty_oneWaySet(obj, keyName, value) { _emberMetalProperties.defineProperty(obj, keyName, null); return _emberMetalProperty_set.set(obj, keyName, value); } // Backwards compatibility with Ember Data AliasedProperty.prototype._meta = undefined; AliasedProperty.prototype.meta = _emberMetalComputed.ComputedProperty.prototype.meta; }); // Ember.assert enifed("ember-metal/array", ["exports"], function (exports) { /** @module ember @submodule 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 @public */ 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, _emberMetalCore, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalUtils, _emberMetalObserver, _emberMetalRun_loop, _emberMetalPath_cache) { exports.bind = bind; exports.oneWay = oneWay; // ES6TODO: where is Ember.lookup defined? /** @module ember @submodule ember-metal */ // .......................................................... // CONSTANTS // /** Debug parameter you can turn on. This will log all bindings that fire to the console. This should be disabled in production code. Note that you can also enable this from the console or temporarily. @property LOG_BINDINGS @for Ember @type Boolean @default false @public */ _emberMetalCore["default"].LOG_BINDINGS = false || !!_emberMetalCore["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 _emberMetalProperty_get.get(_emberMetalPath_cache.isGlobal(path) ? _emberMetalCore["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 @public */ Binding.prototype = { /** This copies the Binding so it can be connected to another object. @method copy @return {Ember.Binding} `this` @public */ 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` @public */ 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` @public */ 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` @public */ oneWay: function () { this._oneWay = true; return this; }, /** @method toString @return {String} string representation of binding @public */ toString: function () { var oneWay = this._oneWay ? "[oneWay]" : ""; return "Ember.Binding<" + _emberMetalUtils.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` @public */ connect: function (obj) { _emberMetalCore["default"].assert("Must pass a valid object to Ember.Binding.connect()", !!obj); var fromPath = this._from; var toPath = this._to; _emberMetalProperty_set.trySet(obj, toPath, getWithGlobals(obj, fromPath)); // add an observer on the object to be notified when the binding should be updated _emberMetalObserver.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) { _emberMetalObserver.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` @public */ disconnect: function (obj) { _emberMetalCore["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. _emberMetalObserver.removeObserver(obj, this._from, this, this.fromDidChange); // if the binding is two-way, remove the observer from the target as well if (twoWay) { _emberMetalObserver.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) { _emberMetalRun_loop["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 = _emberMetalCore["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) { _emberMetalCore["default"].Logger.log(" ", this.toString(), "->", fromValue, obj); } if (this._oneWay) { _emberMetalProperty_set.trySet(obj, toPath, fromValue); } else { _emberMetalObserver._suspendObserver(obj, toPath, this, this.toDidChange, function () { _emberMetalProperty_set.trySet(obj, toPath, fromValue); }); } // if we're synchronizing *to* the remote object } else if (direction === "back") { var toValue = _emberMetalProperty_get.get(obj, this._to); if (log) { _emberMetalCore["default"].Logger.log(" ", this.toString(), "<-", toValue, obj); } _emberMetalObserver._suspendObserver(obj, fromPath, this, this.fromDidChange, function () { _emberMetalProperty_set.trySet(_emberMetalPath_cache.isGlobal(fromPath) ? _emberMetalCore["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` @public */ oneWay: function (from, flag) { _emberMetalCore["default"].deprecate("Ember.oneWay has been deprecated. Please use Ember.computed.oneWay instead.", false); 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 @public */ // 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 @public */ 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 @public */ function oneWay(obj, to, from) { return new Binding(to, from).oneWay().connect(obj); } exports.Binding = Binding; exports.isGlobalPath = _emberMetalPath_cache.isGlobal; }); // Ember.Logger, Ember.LOG_BINDINGS, assert enifed('ember-metal/cache', ['exports', 'ember-metal/dictionary'], function (exports, _emberMetalDictionary) { exports["default"] = Cache; function Cache(limit, func) { this.store = _emberMetalDictionary["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 = _emberMetalDictionary["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, _emberMetalCore, _emberMetalProperty_get, _emberMetalUtils, _emberMetalArray, _emberMetalWatch_key) { exports.flushPendingChains = flushPendingChains; exports.finishChains = finishChains; var warn = _emberMetalCore["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 = []; _emberMetalArray.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 = _emberMetalUtils.meta(obj); var nodes = m.chainWatchers; if (!m.hasOwnProperty("chainWatchers")) { // FIXME?! nodes = m.chainWatchers = {}; } if (!nodes[keyName]) { nodes[keyName] = []; } nodes[keyName].push(node); _emberMetalWatch_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; } } } _emberMetalWatch_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 _emberMetalProperty_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 _emberMetalProperty_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 = _emberMetalProperty_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 = _emberMetalProperty_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; var node; if (chains) { for (var key in chains) { node = chains[key]; if (node !== undefined) { node.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++) { var node = chainNodes[i]; if (node) { node.didChange(null); } } } } } // copy chains from prototype chains = m.chains; if (chains && chains.value() !== obj) { _emberMetalUtils.meta(obj).chains = chains = chains.copy(obj); } } } exports.removeChainWatcher = removeChainWatcher; exports.ChainNode = ChainNode; }); // warn, assert, etc; 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, _emberMetalProperty_set, _emberMetalUtils, _emberMetalExpand_properties, _emberMetalError, _emberMetalProperties, _emberMetalProperty_events, _emberMetalDependent_keys) { /** @module ember @submodule ember-metal */ var metaFor = _emberMetalUtils.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 @public */ 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 _emberMetalProperties.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. @public */ 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 @public */ 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 @public */ 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 @public */ ComputedPropertyPrototype.property = function () { var args; var addArg = function (property) { args.push(property); }; args = []; for (var i = 0, l = arguments.length; i < l; i++) { _emberMetalExpand_properties["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 {Object} meta @chainable @public */ 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; _emberMetalDependent_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. @public */ 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); } _emberMetalDependent_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. @public */ 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 _emberMetalError["default"]("Cannot set read-only property \"" + keyName + "\" on object: " + _emberMetalUtils.inspect(obj)); } if (cacheable && cache && cache[keyName] !== undefined) { if (cache[keyName] !== UNDEFINED) { cachedValue = cache[keyName]; } hadCachedValue = true; } if (!setter) { _emberMetalProperties.defineProperty(obj, keyName, null, cachedValue); _emberMetalProperty_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) { _emberMetalProperty_events.propertyWillChange(obj, keyName); } if (hadCachedValue) { cache[keyName] = undefined; } if (cacheable) { if (!hadCachedValue) { _emberMetalDependent_keys.addDependentKeys(this, obj, keyName, meta); } if (!cache) { cache = meta.cache = {}; } if (ret === undefined) { cache[keyName] = UNDEFINED; } else { cache[keyName] = ret; } } if (watched) { _emberMetalProperty_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) { _emberMetalDependent_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 @public */ 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 @public */ 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; }; exports.ComputedProperty = ComputedProperty; exports.computed = computed; exports.cacheFor = cacheFor; }); 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, _emberMetalCore, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalComputed, _emberMetalIs_empty, _emberMetalIs_none, _emberMetalAlias) { 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; /** @module ember @submodule ember-metal */ function getProperties(self, propertyNames) { var ret = {}; for (var i = 0; i < propertyNames.length; i++) { ret[propertyNames[i]] = _emberMetalProperty_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 = _emberMetalComputed.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 @public */ function empty(dependentKey) { return _emberMetalComputed.computed(dependentKey + ".length", function () { return _emberMetalIs_empty["default"](_emberMetalProperty_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. @public */ function notEmpty(dependentKey) { return _emberMetalComputed.computed(dependentKey + ".length", function () { return !_emberMetalIs_empty["default"](_emberMetalProperty_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. @public */ function none(dependentKey) { return _emberMetalComputed.computed(dependentKey, function () { return _emberMetalIs_none["default"](_emberMetalProperty_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 @public */ function not(dependentKey) { return _emberMetalComputed.computed(dependentKey, function () { return !_emberMetalProperty_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 @public */ function bool(dependentKey) { return _emberMetalComputed.computed(dependentKey, function () { return !!_emberMetalProperty_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 @public */ function match(dependentKey, regexp) { return _emberMetalComputed.computed(dependentKey, function () { var value = _emberMetalProperty_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. @public */ function equal(dependentKey, value) { return _emberMetalComputed.computed(dependentKey, function () { return _emberMetalProperty_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. @public */ function gt(dependentKey, value) { return _emberMetalComputed.computed(dependentKey, function () { return _emberMetalProperty_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. @public */ function gte(dependentKey, value) { return _emberMetalComputed.computed(dependentKey, function () { return _emberMetalProperty_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. @public */ function lt(dependentKey, value) { return _emberMetalComputed.computed(dependentKey, function () { return _emberMetalProperty_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. @public */ function lte(dependentKey, value) { return _emberMetalComputed.computed(dependentKey, function () { return _emberMetalProperty_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. @public */ var and = generateComputedWithProperties(function (properties) { var value; for (var key in properties) { value = properties[key]; if (properties.hasOwnProperty(key) && !value) { return false; } } return value; }); exports.and = and; /** A computed property which performs a logical `or` on the original values for the provided dependent properties. Example ```javascript var Hamster = Ember.Object.extend({ readyForRain: Ember.computed.or('hasJacket', 'hasUmbrella') }); var hamster = Hamster.create(); hamster.get('readyForRain'); // false hamster.set('hasUmbrella', true); hamster.get('readyForRain'); // true hamster.set('hasJacket', 'Yes'); hamster.get('readyForRain'); // 'Yes' ``` @method or @for Ember.computed @param {String} dependentKey* @return {Ember.ComputedProperty} computed property which performs a logical `or` on the values of all the original values for properties. @public */ var or = generateComputedWithProperties(function (properties) { for (var key in properties) { if (properties.hasOwnProperty(key) && properties[key]) { return properties[key]; } } return false; }); exports.or = or; /** A computed property that returns the first truthy value from a list of dependent properties. Example ```javascript var Hamster = Ember.Object.extend({ hasClothes: Ember.computed.any('hat', 'shirt') }); var hamster = Hamster.create(); hamster.get('hasClothes'); // null hamster.set('shirt', 'Hawaiian Shirt'); hamster.get('hasClothes'); // 'Hawaiian Shirt' ``` @method any @for Ember.computed @param {String} dependentKey* @return {Ember.ComputedProperty} computed property which returns the first truthy value of given list of properties. @deprecated Use `Ember.computed.or` instead. @public */ var any = generateComputedWithProperties(function (properties) { _emberMetalCore["default"].deprecate("Usage of Ember.computed.any is deprecated, use `Ember.computed.or` instead."); for (var key in properties) { if (properties.hasOwnProperty(key) && properties[key]) { return properties[key]; } } return null; }); exports.any = any; /** A computed property that returns the array of values for the provided dependent properties. Example ```javascript var Hamster = Ember.Object.extend({ clothes: Ember.computed.collect('hat', 'shirt') }); var hamster = Hamster.create(); hamster.get('clothes'); // [null, null] hamster.set('hat', 'Camp Hat'); hamster.set('shirt', 'Camp Shirt'); hamster.get('clothes'); // ['Camp Hat', 'Camp Shirt'] ``` @method collect @for Ember.computed @param {String} dependentKey* @return {Ember.ComputedProperty} computed property which maps values of all passed in properties to an array. @public */ var collect = generateComputedWithProperties(function (properties) { var res = _emberMetalCore["default"].A(); for (var key in properties) { if (properties.hasOwnProperty(key)) { if (_emberMetalIs_none["default"](properties[key])) { res.push(null); } else { res.push(properties[key]); } } } return res; }); exports.collect = collect; /** 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. ```javascript var Person = Ember.Object.extend({ name: 'Alex Matchneer', nomen: Ember.computed.alias('name') }); var alex = Person.create(); alex.get('nomen'); // 'Alex Matchneer' alex.get('name'); // 'Alex Matchneer' alex.set('nomen', '@machty'); alex.get('name'); // '@machty' ``` @method alias @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which creates an alias to the original value for property. @public */ /** Where `computed.alias` aliases `get` and `set`, and allows for bidirectional data flow, `computed.oneWay` only provides an aliased `get`. The `set` will not mutate the upstream property, rather causes the current property to become the value set. This causes the downstream property to permanently diverge from the upstream property. Example ```javascript var User = Ember.Object.extend({ firstName: null, lastName: null, nickName: Ember.computed.oneWay('firstName') }); var teddy = User.create({ firstName: 'Teddy', lastName: 'Zeenny' }); teddy.get('nickName'); // 'Teddy' teddy.set('nickName', 'TeddyBear'); // 'TeddyBear' teddy.get('firstName'); // 'Teddy' ``` @method oneWay @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which creates a one way computed property to the original value for property. @public */ function oneWay(dependentKey) { return _emberMetalAlias["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. @public */ /** 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 @public */ function readOnly(dependentKey) { return _emberMetalAlias["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. @public */ function defaultTo(defaultPath) { return _emberMetalComputed.computed({ get: function (key) { _emberMetalCore["default"].deprecate("Usage of Ember.computed.defaultTo is deprecated, use `Ember.computed.oneWay` instead."); return _emberMetalProperty_get.get(this, defaultPath); }, set: function (key, newValue, cachedValue) { _emberMetalCore["default"].deprecate("Usage of Ember.computed.defaultTo is deprecated, use `Ember.computed.oneWay` instead."); return newValue != null ? newValue : _emberMetalProperty_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 @public */ function deprecatingAlias(dependentKey) { return _emberMetalComputed.computed(dependentKey, { get: function (key) { _emberMetalCore["default"].deprecate("Usage of `" + key + "` is deprecated, use `" + dependentKey + "` instead."); return _emberMetalProperty_get.get(this, dependentKey); }, set: function (key, value) { _emberMetalCore["default"].deprecate("Usage of `" + key + "` is deprecated, use `" + dependentKey + "` instead."); _emberMetalProperty_set.set(this, dependentKey, value); return value; } }); } }); enifed('ember-metal/core', ['exports'], function (exports) { /*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.4 @public */ 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.4' @static @public */ Ember.VERSION = '1.13.4'; /** 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 Object @public */ 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 @public */ 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,"ember-htmlbars-get-helper":false,"ember-htmlbars-helper":true,"ember-htmlbars-dashless-helpers":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 @public */ 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 @public */ 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 @public */ 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 @public */ 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 @public */ 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} @public */ function K() { return this; } exports.K = K; 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, _emberMetalPlatformCreate, _emberMetalWatching) { exports.addDependentKeys = addDependentKeys; exports.removeDependentKeys = removeDependentKeys; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed // "REMOVE_USE_STRICT: true"; /** @module ember @submodule 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] = _emberMetalPlatformCreate["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 _emberMetalWatching.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 _emberMetalWatching.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, _emberMetalCore, _emberMetalPlatformDefine_property, _emberMetalProperties, _emberMetalProperty_get, _emberMetalProperty_set) { exports.deprecateProperty = deprecateProperty; /** Used internally to allow changing properties in a backwards compatible way, and print a helpful deprecation warning. @method deprecateProperty @param {Object} object The object to add the deprecated property to. @param {String} deprecatedKey The property to add (and print deprecation warnings upon accessing). @param {String} newKey The property that will be aliased. @private @since 1.7.0 */ function deprecateProperty(object, deprecatedKey, newKey) { function deprecate() { _emberMetalCore["default"].deprecate("Usage of `" + deprecatedKey + "` is deprecated, use `" + newKey + "` instead."); } if (_emberMetalPlatformDefine_property.hasPropertyAccessors) { _emberMetalProperties.defineProperty(object, deprecatedKey, { configurable: true, enumerable: false, set: function (value) { deprecate(); _emberMetalProperty_set.set(this, newKey, value); }, get: function () { deprecate(); return _emberMetalProperty_get.get(this, newKey); } }); } } }); /** @module ember @submodule ember-metal */ enifed('ember-metal/dictionary', ['exports', 'ember-metal/platform/create'], function (exports, _emberMetalPlatformCreate) { exports["default"] = makeDictionary; // the delete is meant to hint at runtimes that this object should remain in // dictionary mode. This is clearly a runtime specific hack, but currently it // appears worthwhile in some usecases. Please note, these deletes do increase // the cost of creation dramatically over a plain Object.create. And as this // only makes sense for long-lived dictionaries that aren't instantiated often. function makeDictionary(parent) { var dict = _emberMetalPlatformCreate["default"](parent); dict['_dict'] = null; delete dict['_dict']; return dict; } }); enifed('ember-metal/enumerable_utils', ['exports', 'ember-metal/core', 'ember-metal/array'], function (exports, _emberMetalCore, _emberMetalArray) { 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 @deprecated @static @public */ /** Calls the map function on the passed object with a specified callback. This uses `Ember.ArrayPolyfill`'s-map method when necessary. @method map @deprecated Use ES5's Array.prototype.map instead. @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. @public */ function map(obj, callback, thisArg) { return obj.map ? obj.map(callback, thisArg) : _emberMetalArray.map.call(obj, callback, thisArg); } var deprecatedMap = _emberMetalCore["default"].deprecateFunc('Ember.EnumberableUtils.map is deprecated, please refactor to use Array.prototype.map.', map); /** Calls the forEach function on the passed object with a specified callback. This uses `Ember.ArrayPolyfill`'s-forEach method when necessary. @method forEach @deprecated Use ES5's Array.prototype.forEach instead. @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* @public */ function forEach(obj, callback, thisArg) { return obj.forEach ? obj.forEach(callback, thisArg) : _emberMetalArray.forEach.call(obj, callback, thisArg); } var deprecatedForEach = _emberMetalCore["default"].deprecateFunc('Ember.EnumberableUtils.forEach is deprecated, please refactor to use Array.prototype.forEach.', forEach); /** Calls the filter function on the passed object with a specified callback. This uses `Ember.ArrayPolyfill`'s-filter method when necessary. @method filter @deprecated Use ES5's Array.prototype.filter instead. @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 @public */ function filter(obj, callback, thisArg) { return obj.filter ? obj.filter(callback, thisArg) : _emberMetalArray.filter.call(obj, callback, thisArg); } var deprecatedFilter = _emberMetalCore["default"].deprecateFunc('Ember.EnumberableUtils.filter is deprecated, please refactor to use Array.prototype.filter.', filter); /** Calls the indexOf function on the passed object with a specified callback. This uses `Ember.ArrayPolyfill`'s-indexOf method when necessary. @method indexOf @deprecated Use ES5's Array.prototype.indexOf instead. @param {Object} obj The object to call indexOn on @param {Object} index The index to start searching from @public */ function indexOf(obj, element, index) { return obj.indexOf ? obj.indexOf(element, index) : _emberMetalArray.indexOf.call(obj, element, index); } var deprecatedIndexOf = _emberMetalCore["default"].deprecateFunc('Ember.EnumberableUtils.indexOf is deprecated, please refactor to use Array.prototype.indexOf.', indexOf); /** 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 @deprecated @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. @public */ function indexesOf(obj, elements) { return elements === undefined ? [] : map(elements, function (item) { return indexOf(obj, item); }); } var deprecatedIndexesOf = _emberMetalCore["default"].deprecateFunc('Ember.EnumerableUtils.indexesOf is deprecated.', indexesOf); /** Adds an object to an array. If the array already includes the object this method has no effect. @method addObject @deprecated @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' @public */ function addObject(array, item) { var index = indexOf(array, item); if (index === -1) { array.push(item); } } var deprecatedAddObject = _emberMetalCore["default"].deprecateFunc('Ember.EnumerableUtils.addObject is deprecated.', addObject); /** Removes an object from an array. If the array does not contain the passed object this method has no effect. @method removeObject @deprecated @param {Array} array The array to remove the item from. @param {Object} item The item to remove from the passed array. @return 'undefined' @public */ function removeObject(array, item) { var index = indexOf(array, item); if (index !== -1) { array.splice(index, 1); } } var deprecatedRemoveObject = _emberMetalCore["default"].deprecateFunc('Ember.EnumerableUtils.removeObject is deprecated.', removeObject); 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 @deprecated @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. @public */ function replace(array, idx, amt, objects) { if (array.replace) { return array.replace(idx, amt, objects); } else { return _replace(array, idx, amt, objects); } } var deprecatedReplace = _emberMetalCore["default"].deprecateFunc('Ember.EnumerableUtils.replace is deprecated.', replace); /** 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 @deprecated @param {Array} array1 The first array @param {Array} array2 The second array @return {Array} The intersection of the two passed arrays. @public */ function intersection(array1, array2) { var result = []; forEach(array1, function (element) { if (indexOf(array2, element) >= 0) { result.push(element); } }); return result; } var deprecatedIntersection = _emberMetalCore["default"].deprecateFunc('Ember.EnumerableUtils.intersection is deprecated.', intersection); // 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: deprecatedAddObject, filter: deprecatedFilter, forEach: deprecatedForEach, indexOf: deprecatedIndexOf, indexesOf: deprecatedIndexesOf, intersection: deprecatedIntersection, map: deprecatedMap, removeObject: deprecatedRemoveObject, replace: deprecatedReplace }; }); // Ember.deprecateFunc enifed('ember-metal/environment', ['exports', 'ember-metal/core'], function (exports, _emberMetalCore) { /* Ember can run in many different environments, including environments like Node.js where the DOM is unavailable. This object serves as an abstraction over the browser features that Ember relies on, so that code does not explode when trying to boot in an environment that doesn't have them. This is a private abstraction. In the future, we hope that other abstractions (like `Location`, `Renderer`, `dom-helper`) can fully abstract over the differences in environment. */ 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' && !_emberMetalCore["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, _emberMetalPlatformCreate) { 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 @public */ 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 = _emberMetalPlatformCreate["default"](Error.prototype); exports["default"] = EmberError; }); enifed("ember-metal/events", ["exports", "ember-metal/core", "ember-metal/utils", "ember-metal/platform/create"], function (exports, _emberMetalCore, _emberMetalUtils, _emberMetalPlatformCreate) { 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; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed // "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 = _emberMetalUtils.meta(obj, true); var actions; var listeners = meta.listeners; if (!listeners) { listeners = meta.listeners = _emberMetalPlatformCreate["default"](null); listeners.__source__ = obj; } else if (listeners.__source__ !== obj) { // setup inherited copy of the listeners object listeners = meta.listeners = _emberMetalPlatformCreate["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 @public */ function addListener(obj, eventName, target, method, once) { _emberMetalCore["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` @public */ function removeListener(obj, eventName, target, method) { _emberMetalCore["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 _emberMetalUtils.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 _emberMetalUtils.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 @public */ function sendEvent(obj, eventName, params, actions) { // first give object a chance to handle it if (obj !== _emberMetalCore["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) { _emberMetalUtils.applyStr(target, method, params); } else { target[method](); } } else { if (params) { _emberMetalUtils.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 @public */ 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; } exports.removeListener = removeListener; }); /** @module ember @submodule ember-metal */ enifed('ember-metal/expand_properties', ['exports', 'ember-metal/error', 'ember-metal/array'], function (exports, _emberMetalError, _emberMetalArray) { exports["default"] = expandProperties; /** @module ember @submodule ember-metal */ 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 _emberMetalError["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]; _emberMetalArray.forEach.call(parts, function (part, index) { if (part.indexOf(',') >= 0) { properties = duplicateAndReplace(properties, part.split(','), index); } }); _emberMetalArray.forEach.call(properties, function (property) { callback(property.join('')); }); } else { callback(pattern); } } function duplicateAndReplace(properties, currentParts, index) { var all = []; _emberMetalArray.forEach.call(properties, function (property) { _emberMetalArray.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, _emberMetalProperty_get, _emberMetalUtils) { exports["default"] = getProperties; /** To get multiple properties at once, call `Ember.getProperties` with an object followed by a list of strings or an array: ```javascript Ember.getProperties(record, 'firstName', 'lastName', 'zipCode'); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ``` is equivalent to: ```javascript Ember.getProperties(record, ['firstName', 'lastName', 'zipCode']); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ``` @method getProperties @for Ember @param {Object} obj @param {String...|Array} list of keys to get @return {Object} @private */ function getProperties(obj) { var ret = {}; var propertyNames = arguments; var i = 1; if (arguments.length === 2 && _emberMetalUtils.isArray(arguments[1])) { i = 0; propertyNames = arguments[1]; } for (var len = propertyNames.length; i < len; i++) { ret[propertyNames[i]] = _emberMetalProperty_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, _emberMetalCore, _emberMetalComputed, _emberMetalAlias, _emberMetalProperties, _emberMetalPlatformCreate) { /** Read-only property that returns the result of a container lookup. @class InjectedProperty @namespace Ember @constructor @param {String} type The container type the property will lookup @param {String} name (optional) The name the property will lookup, defaults to the property's name @private */ 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; _emberMetalCore["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 = _emberMetalPlatformCreate["default"](_emberMetalProperties.Descriptor.prototype); var InjectedPropertyPrototype = InjectedProperty.prototype; var ComputedPropertyPrototype = _emberMetalComputed.ComputedProperty.prototype; var AliasedPropertyPrototype = _emberMetalAlias.AliasedProperty.prototype; InjectedPropertyPrototype._super$Constructor = _emberMetalComputed.ComputedProperty; InjectedPropertyPrototype.get = ComputedPropertyPrototype.get; InjectedPropertyPrototype.readOnly = ComputedPropertyPrototype.readOnly; InjectedPropertyPrototype.teardown = ComputedPropertyPrototype.teardown; exports["default"] = InjectedProperty; }); // Ember.assert enifed("ember-metal/instrumentation", ["exports", "ember-metal/core", "ember-metal/utils"], function (exports, _emberMetalCore, _emberMetalUtils) { exports.instrument = instrument; exports._instrumentStart = _instrumentStart; exports.subscribe = subscribe; exports.unsubscribe = unsubscribe; exports.reset = reset; /** The purpose of the Ember Instrumentation module is to provide efficient, general-purpose instrumentation for Ember. Subscribe to a listener by using `Ember.subscribe`: ```javascript Ember.subscribe("render", { before: function(name, timestamp, payload) { }, after: function(name, timestamp, payload) { } }); ``` If you return a value from the `before` callback, that same value will be passed as a fourth parameter to the `after` callback. Instrument a block of code by using `Ember.instrument`: ```javascript Ember.instrument("render.handlebars", payload, function() { // rendering logic }, binding); ``` Event names passed to `Ember.instrument` are namespaced by periods, from more general to more specific. Subscribers can listen for events by whatever level of granularity they are interested in. In the above example, the event is `render.handlebars`, and the subscriber listened for all events beginning with `render`. It would receive callbacks for events named `render`, `render.handlebars`, `render.container`, or even `render.handlebars.layout`. @class Instrumentation @namespace Ember @static @private */ var subscribers = []; exports.subscribers = 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. @private */ 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 _emberMetalUtils.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 = _emberMetalCore["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} @private */ 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] @private */ 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 @private */ function reset() { subscribers.length = 0; cache = {}; } }); enifed('ember-metal/is_blank', ['exports', 'ember-metal/is_empty'], function (exports, _emberMetalIs_empty) { exports["default"] = isBlank; /** A value is blank if it is empty or a whitespace string. ```javascript Ember.isBlank(); // true Ember.isBlank(null); // true Ember.isBlank(undefined); // true Ember.isBlank(''); // true Ember.isBlank([]); // true Ember.isBlank('\n\t'); // true Ember.isBlank(' '); // true Ember.isBlank({}); // false Ember.isBlank('\n\t Hello'); // false Ember.isBlank('Hello world'); // false Ember.isBlank([1,2,3]); // false ``` @method isBlank @for Ember @param {Object} obj Value to test @return {Boolean} @since 1.5.0 @public */ function isBlank(obj) { return _emberMetalIs_empty["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, _emberMetalProperty_get, _emberMetalIs_none) { /** Verifies that a value is `null` or an empty string, empty array, or empty function. Constrains the rules on `Ember.isNone` by returning true for empty string and empty arrays. ```javascript Ember.isEmpty(); // true Ember.isEmpty(null); // true Ember.isEmpty(undefined); // true Ember.isEmpty(''); // true Ember.isEmpty([]); // true Ember.isEmpty({}); // false Ember.isEmpty('Adam Hawkins'); // false Ember.isEmpty([0,1,2]); // false ``` @method isEmpty @for Ember @param {Object} obj Value to test @return {Boolean} @public */ function isEmpty(obj) { var none = _emberMetalIs_none["default"](obj); if (none) { return none; } if (typeof obj.size === 'number') { return !obj.size; } var objectType = typeof obj; if (objectType === 'object') { var size = _emberMetalProperty_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 = _emberMetalProperty_get.get(obj, 'length'); if (typeof length === 'number') { return !length; } } return false; } exports["default"] = isEmpty; }); enifed("ember-metal/is_none", ["exports"], function (exports) { /** 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} @public */ function isNone(obj) { return obj === null || obj === undefined; } exports["default"] = isNone; }); enifed('ember-metal/is_present', ['exports', 'ember-metal/is_blank'], function (exports, _emberMetalIs_blank) { exports["default"] = isPresent; /** A value is present if it not `isBlank`. ```javascript Ember.isPresent(); // false Ember.isPresent(null); // false Ember.isPresent(undefined); // false Ember.isPresent(false); // false Ember.isPresent(''); // false Ember.isPresent([]); // false Ember.isPresent('\n\t'); // false Ember.isPresent(' '); // false Ember.isPresent({}); // true Ember.isPresent('\n\t Hello'); // true Ember.isPresent('Hello world'); // true Ember.isPresent([1,2,3]); // true ``` @method isPresent @for Ember @param {Object} obj Value to test @return {Boolean} @since 1.8.0 @public */ function isPresent(obj) { return !_emberMetalIs_blank["default"](obj); } }); enifed('ember-metal/keys', ['exports', 'ember-metal/platform/define_property'], function (exports, _emberMetalPlatformDefine_property) { /** Returns all of the keys defined on an object or hash. This is useful when inspecting objects for debugging. On browsers that support it, this uses the native `Object.keys` implementation. @method keys @for Ember @param {Object} obj @return {Array} Array containing keys of obj @private */ var keys = Object.keys; if (!keys || !_emberMetalPlatformDefine_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, _emberMetalCore, _emberMetalEnumerable_utils) { /** Helper class that allows you to register your library with Ember. Singleton created at `Ember.libraries`. @class Libraries @constructor @private */ 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 { _emberMetalCore["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 = _emberMetalEnumerable_utils.indexOf(this._registry, lib); this._registry.splice(index, 1); } }, each: function (callback) { _emberMetalCore["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."); _emberMetalEnumerable_utils.forEach(this._registry, function (lib) { callback(lib.name, lib.version); }); } }; if (_emberMetalCore["default"].FEATURES.isEnabled("ember-libraries-isregistered")) { Libraries.prototype.isRegistered = function (name) { return !!this._getLibraryByName(name); }; } exports["default"] = Libraries; }); enifed("ember-metal/logger", ["exports", "ember-metal/core", "ember-metal/error"], function (exports, _emberMetalCore, _emberMetalError) { function K() { return this; } function consoleMethod(name) { var consoleObj, logToConsole; if (_emberMetalCore["default"].imports.console) { consoleObj = _emberMetalCore["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 _emberMetalError["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 @private */ 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 @private */ 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 @private */ 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 @private */ 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 @private */ 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 @private */ 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 @private */ assert: consoleMethod("assert") || assertPolyfill }; }); // Ember.imports enifed("ember-metal/map", ["exports", "ember-metal/utils", "ember-metal/array", "ember-metal/platform/create", "ember-metal/deprecate_property"], function (exports, _emberMetalUtils, _emberMetalArray, _emberMetalPlatformCreate, _emberMetalDeprecate_property) { 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 = _emberMetalPlatformCreate["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} @private */ OrderedSet.create = function () { var Constructor = this; return new Constructor(); }; OrderedSet.prototype = { constructor: OrderedSet, /** @method clear @private */ clear: function () { this.presenceSet = _emberMetalPlatformCreate["default"](null); this.list = []; this.size = 0; }, /** @method add @param obj @param guid (optional, and for internal use) @return {Ember.OrderedSet} @private */ add: function (obj, _guid) { var guid = _guid || _emberMetalUtils.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} @private */ 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} @private */ "delete": function (obj, _guid) { var guid = _guid || _emberMetalUtils.guidFor(obj); var presenceSet = this.presenceSet; var list = this.list; if (presenceSet[guid] === true) { delete presenceSet[guid]; var index = _emberMetalArray.indexOf.call(list, obj); if (index > -1) { list.splice(index, 1); } this.size = list.length; return true; } else { return false; } }, /** @method isEmpty @return {Boolean} @private */ isEmpty: function () { return this.size === 0; }, /** @method has @param obj @return {Boolean} @private */ has: function (obj) { if (this.size === 0) { return false; } var guid = _emberMetalUtils.guidFor(obj); var presenceSet = this.presenceSet; return presenceSet[guid] === true; }, /** @method forEach @param {Function} fn @param self @private */ 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} @private */ toArray: function () { return this.list.slice(); }, /** @method copy @return {Ember.OrderedSet} @private */ 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; } }; _emberMetalDeprecate_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 = _emberMetalPlatformCreate["default"](null); this.size = 0; } else { missingNew("OrderedSet"); } } Ember.Map = Map; /** @method create @static @private */ 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 @private */ size: 0, /** Retrieve the value associated with a given key. @method get @param {*} key @return {*} the value associated with the key, or `undefined` @private */ get: function (key) { if (this.size === 0) { return; } var values = this._values; var guid = _emberMetalUtils.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} @private */ set: function (key, value) { var keys = this._keys; var values = this._values; var guid = _emberMetalUtils.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 @private */ 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 @private */ "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 = _emberMetalUtils.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 @private */ 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. @private */ 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 @private */ clear: function () { this._keys.clear(); this._values = _emberMetalPlatformCreate["default"](null); this.size = 0; }, /** @method copy @return {Ember.Map} @private */ copy: function () { return copyMap(this, new Map()); } }; _emberMetalDeprecate_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` @private */ MapWithDefault.create = function (options) { if (options) { return new MapWithDefault(options); } else { return new Map(); } }; MapWithDefault.prototype = _emberMetalPlatformCreate["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 @private */ 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} @private */ MapWithDefault.prototype.copy = function () { var Constructor = this.constructor; return copyMap(this, new Constructor({ defaultValue: this.defaultValue })); }; exports["default"] = Map; exports.OrderedSet = OrderedSet; exports.Map = Map; exports.MapWithDefault = MapWithDefault; }); /** @module ember @submodule 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. */ enifed('ember-metal/merge', ['exports', 'ember-metal/keys'], function (exports, _emberMetalKeys) { exports["default"] = merge; exports.assign = assign; /** Merge the contents of two objects together into the first object. ```javascript Ember.merge({first: 'Tom'}, {last: 'Dale'}); // {first: 'Tom', last: 'Dale'} var a = {first: 'Yehuda'}; var b = {last: 'Katz'}; Ember.merge(a, b); // a == {first: 'Yehuda', last: 'Katz'}, b == {last: 'Katz'} ``` @method merge @for Ember @param {Object} original The object to merge into @param {Object} updates The object to copy properties from @return {Object} @private */ function merge(original, updates) { if (!updates || typeof updates !== 'object') { return original; } var props = _emberMetalKeys["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; } var updates = _emberMetalKeys["default"](arg); for (var _i = 0, _l = updates.length; _i < _l; _i++) { var prop = updates[_i]; 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, _emberMetalCore, _emberMetalMerge, _emberMetalArray, _emberMetalPlatformCreate, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalUtils, _emberMetalExpand_properties, _emberMetalProperties, _emberMetalComputed, _emberMetalBinding, _emberMetalObserver, _emberMetalEvents, _emberMetalStreamsUtils) { exports.mixin = mixin; exports.required = required; exports.aliasMethod = aliasMethod; exports.observer = observer; exports._immediateObserver = _immediateObserver; exports._beforeObserver = _beforeObserver; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed // "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 = _emberMetalUtils.meta(obj, true); var ret = m.mixins; if (!ret) { ret = m.mixins = {}; } else if (!m.hasOwnProperty("mixins")) { ret = m.mixins = _emberMetalPlatformCreate["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 = _emberMetalUtils.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 _emberMetalComputed.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 = _emberMetalPlatformCreate["default"](property); property._getter = _emberMetalUtils.wrap(property._getter, superProperty._getter); if (superProperty._setter) { if (property._setter) { property._setter = _emberMetalUtils.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 _emberMetalUtils.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 _emberMetalUtils.makeArray(baseValue).concat(value); } } else { return _emberMetalUtils.makeArray(value); } } function applyMergedProperties(obj, key, value, values) { var baseValue = values[key] || obj[key]; _emberMetalCore["default"].assert("You passed in `" + JSON.stringify(value) + "` as the value for `" + key + "` but `" + key + "` cannot be an Array", !_emberMetalUtils.isArray(value)); if (!baseValue) { return value; } var newBase = _emberMetalMerge["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 _emberMetalProperties.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 && _emberMetalArray.indexOf.call(concats, key) >= 0 || key === "concatenatedProperties" || key === "mergedProperties") { value = applyConcatenatedProperties(base, key, value, values); } else if (mergings && _emberMetalArray.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]; _emberMetalCore["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 = _emberMetalUtils.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) { _emberMetalArray.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 = _emberMetalPlatformCreate["default"](m.bindings); } bindings[key] = value; } } function connectStreamBinding(obj, key, stream) { var onNotify = function (stream) { _emberMetalObserver._suspendObserver(obj, key, null, didChange, function () { _emberMetalProperty_set.trySet(obj, key, stream.value()); }); }; var didChange = function () { stream.setValue(_emberMetalProperty_get.get(obj, key), onNotify); }; // Initialize value _emberMetalProperty_set.set(obj, key, stream.value()); _emberMetalObserver.addObserver(obj, key, null, didChange); stream.subscribe(onNotify); if (obj._streamBindingSubscriptions === undefined) { obj._streamBindingSubscriptions = _emberMetalPlatformCreate["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 (_emberMetalStreamsUtils.isStream(binding)) { connectStreamBinding(obj, to, binding); continue; } else if (binding instanceof _emberMetalBinding.Binding) { binding = binding.copy(); // copy prototypes' instance binding.to(to); } else { // binding is string path binding = new _emberMetalBinding.Binding(to, binding); } binding.connect(obj); obj[key] = binding; } } // mark as applied m.bindings = {}; } } function finishPartial(obj, m) { connectBindings(obj, m || _emberMetalUtils.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__", _emberMetalObserver._removeBeforeObserver); updateObserversAndListeners(obj, key, prev, "__ember_observes__", _emberMetalObserver.removeObserver); updateObserversAndListeners(obj, key, prev, "__ember_listens__", _emberMetalEvents.removeListener); } if ("function" === typeof observerOrListener) { updateObserversAndListeners(obj, key, observerOrListener, "__ember_observesBefore__", _emberMetalObserver._addBeforeObserver); updateObserversAndListeners(obj, key, observerOrListener, "__ember_observes__", _emberMetalObserver.addObserver); updateObserversAndListeners(obj, key, observerOrListener, "__ember_listens__", _emberMetalEvents.addListener); } } function applyMixin(obj, mixins, partial) { var descs = {}; var values = {}; var m = _emberMetalUtils.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); _emberMetalProperties.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 @private */ 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 @public */ 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? _emberMetalCore["default"].anyUnprocessedMixins = false; /** @method create @static @param arguments* @public */ Mixin.create = function () { // ES6TODO: this relies on a global state? _emberMetalCore["default"].anyUnprocessedMixins = true; var M = this; for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return new M(args, undefined); }; var MixinPrototype = Mixin.prototype; /** @method reopen @param arguments* @private */ 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]; _emberMetalCore["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 @private */ 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 = _emberMetalUtils.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} @private */ 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[_emberMetalUtils.guidFor(this)]; } return false; }; MixinPrototype.without = function () { var ret = new Mixin([this]); for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } ret._without = args; return ret; }; function _keys(ret, mixin, seen) { if (seen[_emberMetalUtils.guidFor(mixin)]) { return; } seen[_emberMetalUtils.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) { _emberMetalArray.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; }; exports.REQUIRED = REQUIRED = new _emberMetalProperties.Descriptor(); REQUIRED.toString = function () { return "(Required Property)"; }; /** Denotes a required property for a mixin @method required @for Ember @private */ function required() { _emberMetalCore["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 _emberMetalProperties.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 @private */ 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 }) }); ``` Also available as `Function.prototype.observes` if prototype extensions are enabled. @method observer @for Ember @param {String} propertyNames* @param {Function} func @return func @private */ 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) { _emberMetalExpand_properties["default"](_paths[i], addWatchedProperty); } if (typeof func !== "function") { throw new _emberMetalCore["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 @deprecated Use `Ember.observer` instead. @return func @private */ function _immediateObserver() { _emberMetalCore["default"].deprecate("Usage of `Ember.immediateObserver` is deprecated, use `Ember.observer` instead."); for (var i = 0, l = arguments.length; i < l; i++) { var arg = arguments[i]; _emberMetalCore["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 @deprecated @private */ 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) { _emberMetalExpand_properties["default"](_paths[i], addWatchedProperty); } if (typeof func !== "function") { throw new _emberMetalCore["default"].Error("Ember.beforeObserver called without a function"); } func.__ember_observesBefore__ = paths; return func; } exports.IS_BINDING = IS_BINDING; exports.Mixin = Mixin; exports.required = required; exports.REQUIRED = REQUIRED; }); /** @module ember @submodule ember-metal */ // warn, assert, wrap, et; enifed("ember-metal/observer", ["exports", "ember-metal/watching", "ember-metal/array", "ember-metal/events"], function (exports, _emberMetalWatching, _emberMetalArray, _emberMetalEvents) { 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; /** @module ember-metal */ 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} target @param {Function|String} [method] @public */ function addObserver(obj, _path, target, method) { _emberMetalEvents.addListener(obj, changeEvent(_path), target, method); _emberMetalWatching.watch(obj, _path); return this; } function observersFor(obj, path) { return _emberMetalEvents.listenersFor(obj, changeEvent(path)); } /** @method removeObserver @for Ember @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] @public */ function removeObserver(obj, path, target, method) { _emberMetalWatching.unwatch(obj, path); _emberMetalEvents.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] @deprecated @private */ function _addBeforeObserver(obj, path, target, method) { _emberMetalEvents.addListener(obj, beforeEvent(path), target, method); _emberMetalWatching.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 _emberMetalEvents.suspendListener(obj, beforeEvent(path), target, method, callback); } function _suspendObserver(obj, path, target, method, callback) { return _emberMetalEvents.suspendListener(obj, changeEvent(path), target, method, callback); } function _suspendBeforeObservers(obj, paths, target, method, callback) { var events = _emberMetalArray.map.call(paths, beforeEvent); return _emberMetalEvents.suspendListeners(obj, events, target, method, callback); } function _suspendObservers(obj, paths, target, method, callback) { var events = _emberMetalArray.map.call(paths, changeEvent); return _emberMetalEvents.suspendListeners(obj, events, target, method, callback); } function _beforeObserversFor(obj, path) { return _emberMetalEvents.listenersFor(obj, beforeEvent(path)); } /** @method removeBeforeObserver @for Ember @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] @deprecated @private */ function _removeBeforeObserver(obj, path, target, method) { _emberMetalWatching.unwatch(obj, path); _emberMetalEvents.removeListener(obj, beforeEvent(path), target, method); return this; } }); enifed("ember-metal/observer_set", ["exports", "ember-metal/utils", "ember-metal/events"], function (exports, _emberMetalUtils, _emberMetalEvents) { /* this.observerSet = { [senderGuid]: { // variable name: `keySet` [keyName]: listIndex } }, this.observers = [ { sender: obj, keyName: keyName, eventName: eventName, listeners: [ [target, method, flags] ] }, ... ] */ exports["default"] = ObserverSet; function ObserverSet() { this.clear(); } ObserverSet.prototype.add = function (sender, keyName, eventName) { var observerSet = this.observerSet; var observers = this.observers; var senderGuid = _emberMetalUtils.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; } _emberMetalEvents.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, _emberMetalCache) { 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 _emberMetalCache["default"](1000, function (key) { return IS_GLOBAL.test(key); }); var isGlobalPathCache = new _emberMetalCache["default"](1000, function (key) { return IS_GLOBAL_PATH.test(key); }); var hasThisCache = new _emberMetalCache["default"](1000, function (key) { return key.lastIndexOf(HAS_THIS, 0) === 0; }); var firstDotIndexCache = new _emberMetalCache["default"](1000, function (key) { return key.indexOf('.'); }); var firstKeyCache = new _emberMetalCache["default"](1000, function (path) { var index = firstDotIndexCache.get(path); if (index === -1) { return path; } else { return path.slice(0, index); } }); var tailPathCache = new _emberMetalCache["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 }; exports.caches = caches; 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); } }); enifed('ember-metal/platform/create', ['exports', 'ember-metal/platform/define_properties'], function (exports, _emberMetalPlatformDefine_properties) { // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed // 'REMOVE_USE_STRICT: true'; /** @class platform @namespace Ember @static @private */ /** Identical to `Object.create()`. Implements if not available natively. @since 1.8.0 @method create @for Ember @public */ 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) { _emberMetalPlatformDefine_properties["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, _emberMetalPlatformDefine_property) { 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__") { _emberMetalPlatformDefine_property.defineProperty(object, property, properties[property]); } } return object; }; Object.defineProperties = defineProperties; } exports["default"] = defineProperties; }); enifed('ember-metal/platform/define_property', ['exports'], function (exports) { /*globals Node */ /** @class platform @namespace Ember @static @private */ /** Set to true if the platform supports native getters and setters. @property hasPropertyAccessors @final @private */ /** 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} @public */ 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) { exports.defineProperty = 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) { exports.defineProperty = 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, _emberMetalCore, _emberMetalUtils, _emberMetalPlatformDefine_property, _emberMetalProperty_events) { exports.Descriptor = Descriptor; exports.MANDATORY_SETTER_FUNCTION = MANDATORY_SETTER_FUNCTION; exports.DEFAULT_GETTER_FUNCTION = DEFAULT_GETTER_FUNCTION; exports.defineProperty = defineProperty; // .......................................................... // DESCRIPTOR // /** Objects of this type can implement an interface to respond to requests to get and set. The default implementation handles simple properties. @class Descriptor @private */ function Descriptor() { this.isDescriptor = true; } // .......................................................... // DEFINING PROPERTIES API // function MANDATORY_SETTER_FUNCTION(name) { return function SETTER_FUNCTION(value) { _emberMetalCore["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 = _emberMetalUtils.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 (_emberMetalCore["default"].FEATURES.isEnabled("mandatory-setter")) { if (watching && _emberMetalPlatformDefine_property.hasPropertyAccessors) { _emberMetalPlatformDefine_property.defineProperty(obj, keyName, { configurable: true, enumerable: true, writable: true, value: value }); } else { obj[keyName] = value; } } else { obj[keyName] = value; } if (desc.setup) { desc.setup(obj, keyName); } } else { if (desc == null) { value = data; if (_emberMetalCore["default"].FEATURES.isEnabled("mandatory-setter")) { if (watching && _emberMetalPlatformDefine_property.hasPropertyAccessors) { meta.values[keyName] = data; _emberMetalPlatformDefine_property.defineProperty(obj, keyName, { configurable: true, enumerable: true, set: MANDATORY_SETTER_FUNCTION(keyName), get: DEFAULT_GETTER_FUNCTION(keyName) }); } else { obj[keyName] = data; } } else { obj[keyName] = data; } } else { value = desc; // compatibility with ES5 _emberMetalPlatformDefine_property.defineProperty(obj, keyName, desc); } } // if key is being watched, override chains that // were initialized with the prototype if (watching) { _emberMetalProperty_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; } }); /** @module ember-metal */ enifed("ember-metal/property_events", ["exports", "ember-metal/utils", "ember-metal/events", "ember-metal/observer_set"], function (exports, _emberMetalUtils, _emberMetalEvents, _emberMetalObserver_set) { var PROPERTY_DID_CHANGE = _emberMetalUtils.symbol("PROPERTY_DID_CHANGE"); exports.PROPERTY_DID_CHANGE = PROPERTY_DID_CHANGE; var beforeObserverSet = new _emberMetalObserver_set["default"](); var observerSet = new _emberMetalObserver_set["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} @private */ 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} @private */ 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 = _emberMetalUtils.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] @private */ function changeProperties(callback, binding) { beginPropertyChanges(); _emberMetalUtils.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 = _emberMetalEvents.accumulateListeners(obj, eventName, listeners); _emberMetalEvents.sendEvent(obj, eventName, [obj, keyName], added); } else { _emberMetalEvents.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); _emberMetalEvents.accumulateListeners(obj, eventName, listeners); } else { _emberMetalEvents.sendEvent(obj, eventName, [obj, keyName]); } } exports.propertyWillChange = propertyWillChange; exports.propertyDidChange = propertyDidChange; exports.overrideChains = overrideChains; exports.beginPropertyChanges = beginPropertyChanges; exports.endPropertyChanges = endPropertyChanges; exports.changeProperties = changeProperties; }); 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, _emberMetalCore, _emberMetalError, _emberMetalPath_cache, _emberMetalPlatformDefine_property, _emberMetalUtils, _emberMetalIs_none) { exports.get = get; exports.normalizeTuple = normalizeTuple; exports._getPath = _getPath; exports.getWithDefault = getWithDefault; var FIRST_KEY = /^([^\.]+)/; var INTERCEPT_GET = _emberMetalUtils.symbol("INTERCEPT_GET"); exports.INTERCEPT_GET = INTERCEPT_GET; var UNHANDLED_GET = _emberMetalUtils.symbol("UNHANDLED_GET"); exports.UNHANDLED_GET = UNHANDLED_GET; // .......................................................... // GET AND SET // // If we are on a platform that supports accessors we can use those. // Otherwise simulate accessors by looking up the property directly on the // object. /** Gets the value of a property on an object. If the property is computed, the function will be invoked. If the property is not defined but the object implements the `unknownProperty` method then that will be invoked. If you plan to run on IE8 and older browsers then you should use this method anytime you want to retrieve a property on an object that you don't know for sure is private. (Properties beginning with an underscore '_' are considered private.) On all newer browsers, you only need to use this method to retrieve properties if the property might not be defined on the object and you want to respect the `unknownProperty` handler. Otherwise you can ignore this method. Note that if the object itself is `undefined`, this method will throw an error. @method get @for Ember @param {Object} obj The object to retrieve from. @param {String} keyName The property key to retrieve @return {Object} the property value or `null`. @public */ function get(obj, keyName) { // Helpers that operate with 'this' within an #each if (keyName === "") { return obj; } if (!keyName && "string" === typeof obj) { keyName = obj; obj = _emberMetalCore["default"].lookup; } _emberMetalCore["default"].assert("Cannot call get with " + keyName + " key.", !!keyName); _emberMetalCore["default"].assert("Cannot call get with '" + keyName + "' on an undefined object.", obj !== undefined); if (_emberMetalIs_none["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 && _emberMetalPath_cache.isPath(keyName)) { return _getPath(obj, keyName); } if (desc) { return desc.get(obj, keyName); } else { if (_emberMetalCore["default"].FEATURES.isEnabled("mandatory-setter")) { if (_emberMetalPlatformDefine_property.hasPropertyAccessors && meta && meta.watching[keyName] > 0) { ret = meta.values[keyName]; } else { ret = obj[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 = _emberMetalPath_cache.hasThis(path); var isGlobal = !hasThis && _emberMetalPath_cache.isGlobal(path); var key; if (!target && !isGlobal) { return [undefined, ""]; } if (hasThis) { path = path.slice(5); } if (!target || isGlobal) { target = _emberMetalCore["default"].lookup; } if (isGlobal && _emberMetalPath_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 _emberMetalError["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 = _emberMetalPath_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; }); /** @module ember-metal */ 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, _emberMetalCore, _emberMetalProperty_get, _emberMetalProperty_events, _emberMetalProperties, _emberMetalError, _emberMetalPath_cache, _emberMetalPlatformDefine_property, _emberMetalUtils) { exports.set = set; exports.trySet = trySet; var INTERCEPT_SET = _emberMetalUtils.symbol("INTERCEPT_SET"); exports.INTERCEPT_SET = INTERCEPT_SET; var UNHANDLED_SET = _emberMetalUtils.symbol("UNHANDLED_SET"); exports.UNHANDLED_SET = UNHANDLED_SET; /** Sets the value of a property on an object, respecting computed properties and notifying observers and other listeners of the change. If the property is not defined but the object implements the `setUnknownProperty` method then that will be invoked as well. @method set @for Ember @param {Object} obj The object to modify. @param {String} keyName The property key to set @param {Object} value The value to set @return {Object} the passed value. @public */ function set(obj, keyName, value, tolerant) { if (typeof obj === "string") { _emberMetalCore["default"].assert("Path '" + obj + "' must be global if no obj is given.", _emberMetalPath_cache.isGlobalPath(obj)); value = keyName; keyName = obj; obj = _emberMetalCore["default"].lookup; } _emberMetalCore["default"].assert("Cannot call set with '" + keyName + "' key.", !!keyName); if (obj === _emberMetalCore["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) && _emberMetalPath_cache.isPath(keyName)) { return setPath(obj, keyName, value, tolerant); } _emberMetalCore["default"].assert("You need to provide an object and key to `set`.", !!obj && keyName !== undefined); _emberMetalCore["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 (_emberMetalCore["default"].FEATURES.isEnabled("mandatory-setter")) { if (_emberMetalPlatformDefine_property.hasPropertyAccessors) { currentValue = meta.values[keyName]; } else { currentValue = obj[keyName]; } } else { currentValue = obj[keyName]; } } // only trigger a change if the value has changed if (value !== currentValue) { _emberMetalProperty_events.propertyWillChange(obj, keyName); if (_emberMetalCore["default"].FEATURES.isEnabled("mandatory-setter")) { if (_emberMetalPlatformDefine_property.hasPropertyAccessors) { if (currentValue === undefined && !(keyName in obj) || !Object.prototype.propertyIsEnumerable.call(obj, keyName)) { _emberMetalProperties.defineProperty(obj, keyName, null, value); // setup mandatory setter } else { meta.values[keyName] = value; } } else { obj[keyName] = value; } } else { obj[keyName] = value; } _emberMetalProperty_events.propertyDidChange(obj, keyName); } } else { obj[keyName] = value; if (obj[_emberMetalProperty_events.PROPERTY_DID_CHANGE]) { obj[_emberMetalProperty_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 = _emberMetalProperty_get._getPath(root, path); } if (!keyName || keyName.length === 0) { throw new _emberMetalError["default"]("Property set failed: You passed an empty path"); } if (!root) { if (tolerant) { return; } else { throw new _emberMetalError["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} root The object to modify. @param {String} path The property path to set @param {Object} value The value to set @public */ function trySet(root, path, value) { return set(root, path, value, true); } }); enifed('ember-metal/run_loop', ['exports', 'ember-metal/core', 'ember-metal/utils', 'ember-metal/array', 'ember-metal/property_events', 'backburner'], function (exports, _emberMetalCore, _emberMetalUtils, _emberMetalArray, _emberMetalProperty_events, _backburner) { 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: _emberMetalUtils.GUID_KEY, sync: { before: _emberMetalProperty_events.beginPropertyChanges, after: _emberMetalProperty_events.endPropertyChanges }, defaultQueue: 'actions', onBegin: onBegin, onEnd: onEnd, onErrorTarget: _emberMetalCore["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. @public */ 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. @public */ 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 @public */ 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} @public */ 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} @public */ 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'] @private */ /** 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} @public */ 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} @private */ 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`. @public */ 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`. @public */ run.once = function () { checkAutoRun(); for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } 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`. @public */ 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`. @public */ 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 @public */ 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`. @public */ 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`. @public */ run.throttle = function () { return backburner.throttle.apply(backburner, arguments); }; // Make sure it's not an autorun during testing function checkAutoRun() { if (!run.currentRunLoop) { _emberMetalCore["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', !_emberMetalCore["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 (_emberMetalArray.indexOf.call(run.queues, name) === -1) { run.queues.splice(_emberMetalArray.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, _emberMetalProperty_events, _emberMetalProperty_set, _emberMetalKeys) { exports["default"] = setProperties; /** Set a list of properties on an object. These properties are set inside a single `beginPropertyChanges` and `endPropertyChanges` batch, so observers will be buffered. ```javascript var anObject = Ember.Object.create(); anObject.setProperties({ firstName: 'Stanley', lastName: 'Stuart', age: 21 }); ``` @method setProperties @param obj @param {Object} properties @return obj @public */ function setProperties(obj, properties) { if (!properties || typeof properties !== "object") { return obj; } _emberMetalProperty_events.changeProperties(function () { var props = _emberMetalKeys["default"](properties); var propertyName; for (var i = 0, l = props.length; i < l; i++) { propertyName = props[i]; _emberMetalProperty_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, _emberMetalStreamsStream, _emberMetalStreamsUtils, _emberMetalPlatformCreate) { exports["default"] = conditional; function conditional(test, consequent, alternate) { if (_emberMetalStreamsUtils.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 = _emberMetalPlatformCreate["default"](_emberMetalStreamsStream["default"].prototype); ConditionalStream.prototype.compute = function () { var oldTestResult = this.oldTestResult; var newTestResult = !!_emberMetalStreamsUtils.read(this.test); if (newTestResult !== oldTestResult) { switch (oldTestResult) { case true: _emberMetalStreamsUtils.unsubscribe(this.consequent, this.notify, this);break; case false: _emberMetalStreamsUtils.unsubscribe(this.alternate, this.notify, this);break; case undefined: _emberMetalStreamsUtils.subscribe(this.test, this.notify, this); } switch (newTestResult) { case true: _emberMetalStreamsUtils.subscribe(this.consequent, this.notify, this);break; case false: _emberMetalStreamsUtils.subscribe(this.alternate, this.notify, this); } this.oldTestResult = newTestResult; } return newTestResult ? _emberMetalStreamsUtils.read(this.consequent) : _emberMetalStreamsUtils.read(this.alternate); }; }); enifed("ember-metal/streams/dependency", ["exports", "ember-metal/core", "ember-metal/merge", "ember-metal/streams/utils"], function (exports, _emberMetalCore, _emberMetalMerge, _emberMetalStreamsUtils) { /** @module ember-metal */ /** @private @class Dependency @namespace Ember.streams @constructor */ function Dependency(depender, dependee) { _emberMetalCore["default"].assert("Dependency error: Depender must be a stream", _emberMetalStreamsUtils.isStream(depender)); this.next = null; this.prev = null; this.depender = depender; this.dependee = dependee; this.unsubscription = null; } _emberMetalMerge["default"](Dependency.prototype, { subscribe: function () { _emberMetalCore["default"].assert("Dependency error: Dependency tried to subscribe while already subscribed", !this.unsubscription); this.unsubscription = _emberMetalStreamsUtils.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 _emberMetalStreamsUtils.read(this.dependee); }, setValue: function (value) { return _emberMetalStreamsUtils.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, _emberMetalCore, _emberMetalMerge, _emberMetalPlatformCreate, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalObserver, _emberMetalStreamsStream, _emberMetalStreamsUtils) { function KeyStream(source, key) { _emberMetalCore["default"].assert('KeyStream error: source must be a stream', _emberMetalStreamsUtils.isStream(source)); // TODO: This isn't necessary. _emberMetalCore["default"].assert('KeyStream error: key must be a non-empty string', typeof key === 'string' && key.length > 0); _emberMetalCore["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 = _emberMetalPlatformCreate["default"](_emberMetalStreamsStream["default"].prototype); _emberMetalMerge["default"](KeyStream.prototype, { compute: function () { var object = this.sourceDep.getValue(); if (object) { return _emberMetalProperty_get.get(object, this.key); } }, setValue: function (value) { var object = this.sourceDep.getValue(); if (object) { _emberMetalProperty_set.set(object, this.key, value); } }, setSource: function (source) { this.sourceDep.replace(source); this.notify(); }, _super$revalidate: _emberMetalStreamsStream["default"].prototype.revalidate, revalidate: function (value) { this._super$revalidate(value); var object = this.sourceDep.getValue(); if (object !== this.observedObject) { this._clearObservedObject(); if (object && typeof object === 'object') { _emberMetalObserver.addObserver(object, this.key, this, this.notify); this.observedObject = object; } } }, _super$deactivate: _emberMetalStreamsStream["default"].prototype.deactivate, _clearObservedObject: function () { if (this.observedObject) { _emberMetalObserver.removeObserver(this.observedObject, this.key, this, this.notify); this.observedObject = null; } }, deactivate: function () { this._super$deactivate(); this._clearObservedObject(); } }); exports["default"] = KeyStream; }); enifed("ember-metal/streams/proxy-stream", ["exports", "ember-metal/merge", "ember-metal/streams/stream", "ember-metal/platform/create"], function (exports, _emberMetalMerge, _emberMetalStreamsStream, _emberMetalPlatformCreate) { function ProxyStream(source, label) { this.init(label); this.sourceDep = this.addMutableDependency(source); } ProxyStream.prototype = _emberMetalPlatformCreate["default"](_emberMetalStreamsStream["default"].prototype); _emberMetalMerge["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, _emberMetalCore, _emberMetalPlatformCreate, _emberMetalPath_cache, _emberMetalObserver, _emberMetalStreamsUtils, _emberMetalStreamsSubscriber, _emberMetalStreamsDependency) { /** @module ember-metal */ /** @private @class Stream @namespace Ember.stream @constructor */ 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 || _emberMetalCore["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 = _emberMetalPlatformCreate["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 = _emberMetalPath_cache.getFirstKey(path); var tailPath = _emberMetalPath_cache.getTailPath(path); if (this.children === undefined) { this.children = _emberMetalPlatformCreate["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 _emberMetalStreamsDependency["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 (_emberMetalStreamsUtils.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._clearObservedProxy(); ProxyMixin = ProxyMixin || _emberMetalCore["default"].__loader.require("ember-runtime/mixins/-proxy")["default"]; if (ProxyMixin.detect(value)) { _emberMetalObserver.addObserver(value, "content", this, this.notify); this.observedProxy = value; } } }, _clearObservedProxy: function () { if (this.observedProxy) { _emberMetalObserver.removeObserver(this.observedProxy, "content", this, this.notify); this.observedProxy = null; } }, deactivate: function () { this._clearObservedProxy(); }, 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) { _emberMetalCore["default"].assert("You tried to subscribe to a stream but the callback provided was not a function.", typeof callback === "function"); var subscriber = new _emberMetalStreamsSubscriber["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 (_emberMetalStreamsUtils.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, _emberMetalMerge) { /** @module ember-metal */ /** @private @class Subscriber @namespace Ember.streams @constructor */ function Subscriber(callback, context) { this.next = null; this.prev = null; this.callback = callback; this.context = context; } _emberMetalMerge["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) { 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; /* Check whether an object is a stream or not @public @for Ember.stream @function isStream @param {Object|Stream} object object to check whether it is a stream @return {Boolean} `true` if the object is a stream, `false` otherwise */ 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", ["exports"], function (exports) {}); enifed("ember-metal/utils", ["exports", "ember-metal/core", "ember-metal/platform/create", "ember-metal/platform/define_property"], function (exports, _emberMetalCore, _emberMetalPlatformCreate, _emberMetalPlatformDefine_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; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed // "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 }; exports.GUID_DESC = GUID_DESC; 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 }; exports.EMBER_META_PROPERTY = EMBER_META_PROPERTY; var GUID_KEY_PROPERTY = { name: GUID_KEY, descriptor: nullDescriptor }; exports.GUID_KEY_PROPERTY = GUID_KEY_PROPERTY; var NEXT_SUPER_PROPERTY = { name: "__nextSuper", descriptor: undefinedDescriptor }; exports.NEXT_SUPER_PROPERTY = NEXT_SUPER_PROPERTY; /** Generates a new guid, optionally saving the guid to the object that you pass in. You will rarely need to use this method. Instead you should call `Ember.guidFor(obj)`, which return an existing guid if available. @private @method generateGuid @for Ember @param {Object} [obj] Object the guid will be used for. If passed in, the guid will be saved on the object and reused whenever you pass the same object again. If no object is passed, just generate a new guid. @param {String} [prefix] Prefix to place in front of the guid. Useful when you want to separate the guid into separate namespaces. @return {String} the guid */ 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 { _emberMetalPlatformDefine_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 { _emberMetalPlatformDefine_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 (!_emberMetalPlatformDefine_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 (_emberMetalCore["default"].FEATURES.isEnabled("mandatory-setter")) { if (_emberMetalPlatformDefine_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 (_emberMetalPlatformDefine_property.canDefineNonEnumerableProperties) { if (obj.__defineNonEnumerable) { obj.__defineNonEnumerable(EMBER_META_PROPERTY); } else { _emberMetalPlatformDefine_property.defineProperty(obj, "__ember_meta__", META_DESC); } } ret = new Meta(obj); if (_emberMetalCore["default"].FEATURES.isEnabled("mandatory-setter")) { if (_emberMetalPlatformDefine_property.hasPropertyAccessors) { ret.values = {}; } } obj.__ember_meta__ = ret; } else if (ret.source !== obj) { if (obj.__defineNonEnumerable) { obj.__defineNonEnumerable(EMBER_META_PROPERTY); } else { _emberMetalPlatformDefine_property.defineProperty(obj, "__ember_meta__", META_DESC); } ret = _emberMetalPlatformCreate["default"](ret); ret.watching = _emberMetalPlatformCreate["default"](ret.watching); ret.cache = undefined; ret.cacheMeta = undefined; ret.source = obj; if (_emberMetalCore["default"].FEATURES.isEnabled("mandatory-setter")) { if (_emberMetalPlatformDefine_property.hasPropertyAccessors) { ret.values = _emberMetalPlatformCreate["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) { _emberMetalCore["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] = _emberMetalPlatformCreate["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} @private */ 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 @public */ 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 @private */ var tryFinally; if (needsFinallyFix) { exports.tryFinally = 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 { exports.tryFinally = 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 () { _emberMetalCore["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. @private */ var tryCatchFinally; if (needsFinallyFix) { exports.tryCatchFinally = 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 { exports.tryCatchFinally = 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 () { _emberMetalCore["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} @private */ 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 @private */ 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} t target @param {Function} m method @param {Array} a args @private */ 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} t target @param {String} m method @param {Array} a args @private */ 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_KEY = GUID_KEY; exports.META_DESC = META_DESC; exports.EMPTY_META = EMPTY_META; exports.meta = meta; exports.isArray = isArray; exports.makeArray = makeArray; exports.tryCatchFinally = tryCatchFinally; exports.deprecatedTryCatchFinally = deprecatedTryCatchFinally; exports.canInvoke = canInvoke; 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, _emberMetalCore, _emberMetalUtils, _emberMetalPlatformDefine_property, _emberMetalProperties) { exports.watchKey = watchKey; exports.unwatchKey = unwatchKey; function watchKey(obj, keyName, meta) { // can't watch length on Array - it is special... if (keyName === "length" && _emberMetalUtils.isArray(obj)) { return; } var m = meta || _emberMetalUtils.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 (_emberMetalCore["default"].FEATURES.isEnabled("mandatory-setter")) { if (_emberMetalPlatformDefine_property.hasPropertyAccessors) { handleMandatorySetter(m, obj, keyName); } } } else { watching[keyName] = (watching[keyName] || 0) + 1; } } if (_emberMetalCore["default"].FEATURES.isEnabled("mandatory-setter")) { 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]; _emberMetalPlatformDefine_property.defineProperty(obj, keyName, { configurable: true, enumerable: Object.prototype.propertyIsEnumerable.call(obj, keyName), set: _emberMetalProperties.MANDATORY_SETTER_FUNCTION(keyName), get: _emberMetalProperties.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 || _emberMetalUtils.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 (_emberMetalCore["default"].FEATURES.isEnabled("mandatory-setter")) { if (!desc && _emberMetalPlatformDefine_property.hasPropertyAccessors && keyName in obj) { _emberMetalPlatformDefine_property.defineProperty(obj, keyName, { configurable: true, enumerable: Object.prototype.propertyIsEnumerable.call(obj, keyName), set: function (val) { // redefine to set as enumerable _emberMetalPlatformDefine_property.defineProperty(obj, keyName, { configurable: true, writable: true, enumerable: true, value: val }); delete m.values[keyName]; }, get: _emberMetalProperties.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, _emberMetalUtils, _emberMetalChains) { exports.watchPath = watchPath; exports.unwatchPath = unwatchPath; // get the chains for the current object. If the current object has // chains inherited from the proto they will be cloned and reconfigured for // the current object. function chainsFor(obj, meta) { var m = meta || _emberMetalUtils.meta(obj); var ret = m.chains; if (!ret) { ret = m.chains = new _emberMetalChains.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" && _emberMetalUtils.isArray(obj)) { return; } var m = meta || _emberMetalUtils.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 || _emberMetalUtils.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, _emberMetalUtils, _emberMetalChains, _emberMetalWatch_key, _emberMetalWatch_path, _emberMetalPath_cache) { exports.isWatching = isWatching; exports.unwatch = unwatch; exports.destroy = destroy; /** Starts watching a property on an object. Whenever the property changes, invokes `Ember.propertyWillChange` and `Ember.propertyDidChange`. This is the primitive used by observers and dependent keys; usually you will never call this method directly but instead use higher level methods like `Ember.addObserver()` @private @method watch @for Ember @param obj @param {String} _keyPath */ function watch(obj, _keyPath, m) { // can't watch length on Array - it is special... if (_keyPath === "length" && _emberMetalUtils.isArray(obj)) { return; } if (!_emberMetalPath_cache.isPath(_keyPath)) { _emberMetalWatch_key.watchKey(obj, _keyPath, m); } else { _emberMetalWatch_path.watchPath(obj, _keyPath, m); } } exports.watch = watch; function isWatching(obj, key) { var meta = obj["__ember_meta__"]; return (meta && meta.watching[key]) > 0; } watch.flushPending = _emberMetalChains.flushPendingChains; function unwatch(obj, _keyPath, m) { // can't watch length on Array - it is special... if (_keyPath === "length" && _emberMetalUtils.isArray(obj)) { return; } if (!_emberMetalPath_cache.isPath(_keyPath)) { _emberMetalWatch_key.unwatchKey(obj, _keyPath, m); } else { _emberMetalWatch_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} @private */ 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) { _emberMetalChains.removeChainWatcher(nodeObject, node._key, node); } } } } } } }); /** @module ember-metal */ 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, _emberMetalCore, _emberMetalMerge, _emberHtmlbarsHelpers, _emberHtmlbarsKeywords, _emberRoutingHtmlbarsHelpersQueryParams, _emberRoutingHtmlbarsKeywordsAction, _emberRoutingHtmlbarsKeywordsElementAction, _emberRoutingHtmlbarsKeywordsLinkTo, _emberRoutingHtmlbarsKeywordsRender) { _emberHtmlbarsHelpers.registerHelper("query-params", _emberRoutingHtmlbarsHelpersQueryParams.queryParamsHelper); _emberHtmlbarsKeywords.registerKeyword("action", _emberRoutingHtmlbarsKeywordsAction["default"]); _emberHtmlbarsKeywords.registerKeyword("@element_action", _emberRoutingHtmlbarsKeywordsElementAction["default"]); _emberHtmlbarsKeywords.registerKeyword("link-to", _emberRoutingHtmlbarsKeywordsLinkTo["default"]); _emberHtmlbarsKeywords.registerKeyword("render", _emberRoutingHtmlbarsKeywordsRender["default"]); var deprecatedLinkTo = _emberMetalMerge["default"]({}, _emberRoutingHtmlbarsKeywordsLinkTo["default"]); _emberMetalMerge["default"](deprecatedLinkTo, { link: function (state, params, hash) { _emberRoutingHtmlbarsKeywordsLinkTo["default"].link.call(this, state, params, hash); _emberMetalCore["default"].deprecate("The 'linkTo' view helper is deprecated in favor of 'link-to'"); } }); _emberHtmlbarsKeywords.registerKeyword("linkTo", deprecatedLinkTo); exports["default"] = _emberMetalCore["default"]; }); /** @module ember @submodule ember-routing-htmlbars */ enifed("ember-routing-htmlbars/helpers/query-params", ["exports", "ember-metal/core", "ember-routing/system/query_params"], function (exports, _emberMetalCore, _emberRoutingSystemQuery_params) { exports.queryParamsHelper = queryParamsHelper; /** This is a helper to be used in conjunction with the link-to helper. It will supply url query parameters to the target route. Example ```handlebars {{#link-to 'posts' (query-params direction="asc")}}Sort{{/link-to}} ``` @method query-params @for Ember.Templates.helpers @param {Object} hash takes a hash of query parameters @return {Object} A `QueryParams` object for `{{link-to}}` @public */ function queryParamsHelper(params, hash) { _emberMetalCore["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 _emberRoutingSystemQuery_params["default"].create({ values: hash }); } }); /** @module ember @submodule ember-routing-htmlbars */ // assert enifed("ember-routing-htmlbars/keywords/action", ["exports", "htmlbars-runtime/hooks", "ember-routing-htmlbars/keywords/closure-action"], function (exports, _htmlbarsRuntimeHooks, _emberRoutingHtmlbarsKeywordsClosureAction) { /** The `{{action}}` helper provides a way to pass triggers for behavior (usually just a function) between components, and into components from controllers. ### Passing functions with the action helper There are three contexts an action helper can be used in. The first two contexts to discuss are attribute context, and Handlebars value context. ```handlebars {{! An example of attribute context }}
    {{! Examples of Handlebars value context }} {{input on-input=(action "save")}} {{yield (action "refreshData") andAnotherParam}} ``` In these contexts, the helper is called a "closure action" helper. It's behavior is simple: If passed a function name, read that function off the `actions` property of the current context. Once that function is read (or if a function was passed), create a closure over that function and any arguments. The resulting value of an action helper used this way is simply a function. For example with this attribute context example: ```handlebars {{! An example of attribute context }}
    ``` The resulting template render logic would be: ```js var div = document.createElement('div'); var actionFunction = (function(context){ return function() { return context.actions.save.apply(context, arguments); }; })(context); div.onclick = actionFunction; ``` Thus when the div is clicked, the action on that context is called. Because the `actionFunction` is just a function, closure actions can be passed between components the still execute in the correct context. Here is an example action handler on a component: ```js export default Ember.Component.extend({ actions: { save(/* event *\/) { this.get('model').save(); } } }); ``` Actions are always looked up on the `actions` property of the current context. This avoids collisions in the naming of common actions, such as `destroy`. Two options can be passed to the `action` helper when it is used in this way. * `target=someProperty` will look to `someProperty` instead of the current context for the `actions` hash. This can be useful when targetting a service for actions. * `value="target.value"` will read the path `target.value` off the first argument to the action when it is called and rewrite the first argument to be that value. This is useful when attaching actions to event listeners. ### Invoking an action Closure actions curry both their scope and any arguments. When invoked, any additional arguments are added to the already curried list. Actions should be invoked using the [sendAction](/api/classes/Ember.Component.html#method_sendAction) method. The first argument to `sendAction` is the action to be called, and additional arguments are passed to the action function. This has interesting properties combined with currying of arguments. For example: ```js export default Ember.Component.extend({ actions: { // Usage {{input on-input=(action (action 'setName' model) value="target.value")}} setName(model, name) { model.set('name', name); } } }); ``` The first argument (`model`) was curried over, and the run-time argument (`event`) becomes a second argument. Action calls be nested this way because each simply returns a function. Any function can be passed to the `{{action` helper, including other actions. Actions invoked with `sendAction` have the same currying behavior as demonstrated with `on-input` above. For example: ```js export default Ember.Component.extend({ actions: { setName(model, name) { model.set('name', name); } } }); ``` ```handlebars {{my-input submit=(action 'setName' model)}} ``` ```js // app/components/my-component.js export default Ember.Component.extend({ click() { // Note that model is not passed, it was curried in the template this.sendAction('submit', 'bob'); } }); ``` ### Attaching actions to DOM The third context the `{{action` helper can be used in we call "element space". For example: ```handlebars {{! An example of element space }}
    ``` Used this way, the `{{action}}` helper provides a useful shortcut for registering an HTML element within a template for a single DOM event and forwarding that interaction to the template's context (controller or component). If the context of a template is a controller, actions used this way will bubble to routes when the controller does not implement the specified action. Once an action hits a route, it will bubble through the route hierarchy. ### Event Propagation `{{action` helpers called in element space can control event bubbling. Events triggered through the action helper will automatically have `.preventDefault()` called on them. You do not need to do so in your event handlers. If you need to allow event propagation (to handle file inputs for example) you can supply the `preventDefault=false` option to the `{{action}}` helper: ```handlebars
    ``` To disable bubbling, pass `bubbles=false` to the helper: ```handlebars ``` If you need the default handler to trigger you should either register your own event handler, or use event methods on your view class. See [Ember.View](/api/classes/Ember.View.html) 'Responding to Browser Events' for more information. ### Specifying DOM event type `{{action` helpers called in element space can specify an event type. By default the `{{action}}` helper registers for DOM `click` events. You can supply an `on` option to the helper to specify a different DOM event name: ```handlebars
    click me
    ``` See [Event Names](/api/classes/Ember.View.html#toc_event-names) for a list of acceptable DOM event names. ### Specifying whitelisted modifier keys `{{action` helpers called in element space can specify modifier keys. By default the `{{action}}` helper will ignore click event with pressed modifier keys. You can supply an `allowedKeys` option to specify which keys should not be ignored. ```handlebars
    click me
    ``` This way the `{{action}}` will fire when clicking with the alt key pressed down. Alternatively, supply "any" to the `allowedKeys` option to accept any combination of modifier keys. ```handlebars
    click me with any key pressed
    ``` ### Specifying a Target A `target` option can be provided to the helper to change which object will receive the method call. This option must be a path to an object, accessible in the current context: ```handlebars {{! app/templates/application.hbs }}
    click me
    ``` ```javascript // app/controllers/application.js export default Ember.Controller.extend({ someService: Ember.inject.service() }); ``` @method action @for Ember.Templates.helpers @public */ exports["default"] = function (morph, env, scope, params, hash, template, inverse, visitor) { if (morph) { _htmlbarsRuntimeHooks.keyword("@element_action", morph, env, scope, params, hash, template, inverse, visitor); return true; } return _emberRoutingHtmlbarsKeywordsClosureAction["default"](morph, env, scope, params, hash, template, inverse, visitor); }; }); /** @module ember @submodule ember-templates */ 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", "ember-metal/error"], function (exports, _emberMetalStreamsStream, _emberMetalArray, _emberMetalStreamsUtils, _emberMetalKeys, _emberMetalUtils, _emberMetalProperty_get, _emberMetalError) { exports["default"] = closureAction; var INVOKE = _emberMetalUtils.symbol("INVOKE"); exports.INVOKE = INVOKE; var ACTION = _emberMetalUtils.symbol("ACTION"); exports.ACTION = ACTION; function closureAction(morph, env, scope, params, hash, template, inverse, visitor) { return new _emberMetalStreamsStream["default"](function () { var _this = this; _emberMetalArray.map.call(params, this.addDependency, this); _emberMetalArray.map.call(_emberMetalKeys["default"](hash), function (item) { _this.addDependency(item); }); var rawAction = params[0]; var actionArguments = _emberMetalStreamsUtils.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 = _emberMetalStreamsUtils.read(scope.self); action = _emberMetalStreamsUtils.read(rawAction); if (typeof action === "string") { var actionName = action; action = null; // on-change={{action 'setName'}} if (hash.target) { // on-change={{action 'setName' target=alternativeComponent}} target = _emberMetalStreamsUtils.read(hash.target); } if (target.actions) { action = target.actions[actionName]; } else if (target._actions) { action = target._actions[actionName]; } if (!action) { throw new _emberMetalError["default"]("An action named '" + actionName + "' was not found in " + target + "."); } } } if (hash.value) { //
    // // // // 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, but with a special allowance for disregarding // "); }, pushAttrNode: function (node) { var index = this.attrNodes.length; this.attrNodes[index] = node; }, hydrateMorphs: function (contextualElement) { var childViews = this.childViews; var el = this._element; for (var i = 0, l = childViews.length; i < l; i++) { var childView = childViews[i]; var ref = el.querySelector("#morph-" + i); _emberMetalCore["default"].assert("An error occurred while setting up template bindings. Please check " + (childView && childView.parentView && childView._parentView._debugTemplateName ? "\"" + childView._parentView._debugTemplateName + "\" template " : "") + "for invalid markup or bindings within HTML comments.", ref); var parent = ref.parentNode; childView._morph = this.dom.insertMorphBefore(parent, ref, parent.nodeType === 1 ? parent : contextualElement); parent.removeChild(ref); } }, /** Adds a string of HTML to the `RenderBuffer`. @method push @param {String} string HTML to push into the buffer @chainable @private */ push: function (content) { if (typeof content === "string") { if (this.buffer === null) { this.buffer = ""; } _emberMetalCore["default"].assert("A string cannot be pushed into the buffer after a fragment", !this.buffer.nodeType); this.buffer += content; } else { _emberMetalCore["default"].assert("A fragment cannot be pushed into a buffer that contains content", !this.buffer); this.buffer = content; } return this; }, /** Adds a class to the buffer, which will be rendered to the class attribute. @method addClass @param {String} className Class name to add to the buffer @chainable @private */ addClass: function (className) { // lazily create elementClasses this.elementClasses = this.elementClasses || new ClassSet(); this.elementClasses.add(className); this.classes = this.elementClasses.list; return this; }, setClasses: function (classNames) { this.elementClasses = null; var len = classNames.length; var i; for (i = 0; i < len; i++) { this.addClass(classNames[i]); } }, /** Sets the elementID to be used for the element. @method id @param {String} id @chainable @private */ id: function (id) { this.elementId = id; return this; }, // duck type attribute functionality like jQuery so a render buffer // can be used like a jQuery object in attribute binding scenarios. /** Adds an attribute which will be rendered to the element. @method attr @param {String} name The name of the attribute @param {String} value The value to add to the attribute @chainable @return {Ember.RenderBuffer|String} this or the current attribute value @private */ attr: function (name, value) { var attributes = this.elementAttributes = this.elementAttributes || {}; if (arguments.length === 1) { return attributes[name]; } else { attributes[name] = value; } return this; }, /** Remove an attribute from the list of attributes to render. @method removeAttr @param {String} name The name of the attribute @chainable @private */ removeAttr: function (name) { var attributes = this.elementAttributes; if (attributes) { delete attributes[name]; } return this; }, /** Adds a property which will be rendered to the element. @method prop @param {String} name The name of the property @param {String} value The value to add to the property @chainable @return {Ember.RenderBuffer|String} this or the current property value @private */ prop: function (name, value) { var properties = this.elementProperties = this.elementProperties || {}; if (arguments.length === 1) { return properties[name]; } else { properties[name] = value; } return this; }, /** Remove an property from the list of properties to render. @method removeProp @param {String} name The name of the property @chainable @private */ removeProp: function (name) { var properties = this.elementProperties; if (properties) { delete properties[name]; } return this; }, /** Adds a style to the style attribute which will be rendered to the element. @method style @param {String} name Name of the style @param {String} value @chainable @private */ style: function (name, value) { this.elementStyle = this.elementStyle || {}; this.elementStyle[name] = value; return this; }, generateElement: function () { var tagName = this.tagName; var id = this.elementId; var classes = this.classes; var attrs = this.elementAttributes; var props = this.elementProperties; var style = this.elementStyle; var styleBuffer = ""; var attr, prop, tagString; if (!_emberViewsSystemPlatform.canSetNameOnInputs && attrs && attrs.name) { // IE allows passing a tag to createElement. See note on `canSetNameOnInputs` above as well. tagString = "<" + stripTagName(tagName) + " name=\"" + escapeAttribute(attrs.name) + "\">"; } else { tagString = tagName; } var element = this.dom.createElement(tagString, this.outerContextualElement()); if (id) { this.dom.setAttribute(element, "id", id); this.elementId = null; } if (classes) { this.dom.setAttribute(element, "class", classes.join(" ")); this.classes = null; this.elementClasses = null; } if (style) { for (prop in style) { styleBuffer += prop + ":" + style[prop] + ";"; } this.dom.setAttribute(element, "style", styleBuffer); this.elementStyle = null; } if (attrs) { for (attr in attrs) { this.dom.setAttribute(element, attr, attrs[attr]); } this.elementAttributes = null; } if (props) { for (prop in props) { var _normalizeProperty = _domHelperProp.normalizeProperty(element, prop); var normalized = _normalizeProperty.normalized; this.dom.setPropertyStrict(element, normalized, props[prop]); } this.elementProperties = null; } return this._element = element; }, /** @method element @return {DOMElement} The element corresponding to the generated HTML of this buffer @private */ element: function () { if (this._element && this.attrNodes.length > 0) { var i, l, attrMorph, attrNode; for (i = 0, l = this.attrNodes.length; i < l; i++) { attrNode = this.attrNodes[i]; attrMorph = this.dom.createAttrMorph(this._element, attrNode.attrName); attrNode._morph = attrMorph; } } var content = this.innerContent(); // No content means a text node buffer, with the content // in _element. Ember._BoundView is an example. if (content === null) { return this._element; } var contextualElement = this.innerContextualElement(content); this.dom.detectNamespace(contextualElement); if (!this._element) { this._element = this.dom.createDocumentFragment(); } if (content.nodeType) { this._element.appendChild(content); } else { var frag = this.dom.parseHTML(content, contextualElement); this._element.appendChild(frag); } // This should only happen with legacy string buffers if (this.childViews.length > 0) { this.hydrateMorphs(contextualElement); } return this._element; }, /** Generates the HTML content for this buffer. @method string @return {String} The generated HTML @private */ string: function () { if (this._element) { // Firefox versions < 11 do not have support for element.outerHTML. var thisElement = this.element(); var outerHTML = thisElement.outerHTML; if (typeof outerHTML === "undefined") { return _emberViewsSystemJquery["default"]("
    ").append(thisElement).html(); } return outerHTML; } else { return this.innerString(); } }, outerContextualElement: function () { if (this._outerContextualElement === undefined) { _emberMetalCore["default"].deprecate("The render buffer expects an outer contextualElement to exist." + " This ensures DOM that requires context is correctly generated (tr, SVG tags)." + " Defaulting to document.body, but this will be removed in the future"); this.outerContextualElement = document.body; } return this._outerContextualElement; }, innerContextualElement: function (html) { var innerContextualElement; if (this._element && this._element.nodeType === 1) { innerContextualElement = this._element; } else { innerContextualElement = this.outerContextualElement(); } var omittedStartTag; if (html) { omittedStartTag = detectOmittedStartTag(this.dom, html, innerContextualElement); } return omittedStartTag || innerContextualElement; }, innerString: function () { var content = this.innerContent(); if (content && !content.nodeType) { return content; } }, innerContent: function () { return this.buffer; } }; }); /** @module ember @submodule ember-views */ enifed("ember-views/component_lookup", ["exports", "ember-metal/core", "ember-runtime/system/object", "ember-htmlbars/system/lookup-helper"], function (exports, _emberMetalCore, _emberRuntimeSystemObject, _emberHtmlbarsSystemLookupHelper) { exports["default"] = _emberRuntimeSystemObject["default"].extend({ invalidName: function (name) { if (!_emberHtmlbarsSystemLookupHelper.CONTAINS_DASH_CACHE.get(name)) { _emberMetalCore["default"].assert("You cannot use '" + name + "' as a component name. Component names must contain a hyphen."); return true; } }, lookupFactory: function (name, container) { container = container || this.container; var fullName = "component:" + name; var templateFullName = "template:components/" + name; var templateRegistered = container && container._registry.has(templateFullName); if (templateRegistered) { container._registry.injection(fullName, "layout", templateFullName); } var Component = container.lookupFactory(fullName); // Only treat as a component if either the component // or a template has been registered. if (templateRegistered || Component) { if (!Component) { container._registry.register(fullName, _emberMetalCore["default"].Component); Component = container.lookupFactory(fullName); } return Component; } }, componentFor: function (name, container) { if (this.invalidName(name)) { return; } var fullName = "component:" + name; return container.lookupFactory(fullName); }, layoutFor: function (name, container) { if (this.invalidName(name)) { return; } var templateFullName = "template:components/" + name; return container.lookup(templateFullName); } }); }); enifed("ember-views/mixins/aria_role_support", ["exports", "ember-metal/mixin"], function (exports, _emberMetalMixin) { /** @class AriaRoleSupport @namespace Ember @private */ exports["default"] = _emberMetalMixin.Mixin.create({ attributeBindings: ["ariaRole:role"], /** The WAI-ARIA role of the control represented by this view. For example, a button may have a role of type 'button', or a pane may have a role of type 'alertdialog'. This property is used by assistive software to help visually challenged users navigate rich web applications. The full list of valid WAI-ARIA roles is available at: [http://www.w3.org/TR/wai-aria/roles#roles_categorization](http://www.w3.org/TR/wai-aria/roles#roles_categorization) @property ariaRole @type String @default null @public */ ariaRole: null }); }); /** @module ember @submodule ember-views */ enifed("ember-views/mixins/class_names_support", ["exports", "ember-metal/core", "ember-metal/mixin", "ember-runtime/system/native_array", "ember-metal/utils"], function (exports, _emberMetalCore, _emberMetalMixin, _emberRuntimeSystemNative_array, _emberMetalUtils) { var EMPTY_ARRAY = []; /** @class ClassNamesSupport @namespace Ember @private */ var ClassNamesSupport = _emberMetalMixin.Mixin.create({ concatenatedProperties: ["classNames", "classNameBindings"], init: function () { this._super.apply(this, arguments); _emberMetalCore["default"].assert("Only arrays are allowed for 'classNameBindings'", _emberMetalUtils.isArray(this.classNameBindings)); this.classNameBindings = _emberRuntimeSystemNative_array.A(this.classNameBindings.slice()); _emberMetalCore["default"].assert("Only arrays of static class strings are allowed for 'classNames'. For dynamic classes, use 'classNameBindings'.", _emberMetalUtils.isArray(this.classNames)); this.classNames = _emberRuntimeSystemNative_array.A(this.classNames.slice()); }, /** Standard CSS class names to apply to the view's outer element. This property automatically inherits any class names defined by the view's superclasses as well. @property classNames @type Array @default ['ember-view'] @public */ classNames: ["ember-view"], /** A list of properties of the view to apply as class names. If the property is a string value, the value of that string will be applied as a class name. ```javascript // Applies the 'high' class to the view element Ember.View.extend({ classNameBindings: ['priority'] priority: 'high' }); ``` If the value of the property is a Boolean, the name of that property is added as a dasherized class name. ```javascript // Applies the 'is-urgent' class to the view element Ember.View.extend({ classNameBindings: ['isUrgent'] isUrgent: true }); ``` If you would prefer to use a custom value instead of the dasherized property name, you can pass a binding like this: ```javascript // Applies the 'urgent' class to the view element Ember.View.extend({ classNameBindings: ['isUrgent:urgent'] isUrgent: true }); ``` This list of properties is inherited from the view's superclasses as well. @property classNameBindings @type Array @default [] @public */ classNameBindings: EMPTY_ARRAY }); exports["default"] = ClassNamesSupport; }); /** @module ember @submodule ember-views */ enifed('ember-views/mixins/component_template_deprecation', ['exports', 'ember-metal/core', 'ember-metal/property_get', 'ember-metal/mixin'], function (exports, _emberMetalCore, _emberMetalProperty_get, _emberMetalMixin) { /* The ComponentTemplateDeprecation mixin is used to provide a useful deprecation warning when using either `template` or `templateName` with a component. The `template` and `templateName` properties specified at extend time are moved to `layout` and `layoutName` respectively. This is used internally by Ember in `Ember.Component`. */ exports["default"] = _emberMetalMixin.Mixin.create({ /** @private Moves `templateName` to `layoutName` and `template` to `layout` at extend time if a layout is not also specified. Note that this currently modifies the mixin themselves, which is technically dubious but is practically of little consequence. This may change in the future. @method willMergeMixin @since 1.4.0 */ willMergeMixin: function (props) { // must call _super here to ensure that the ActionHandler // mixin is setup properly (moves actions -> _actions) // // Calling super is only OK here since we KNOW that // there is another Mixin loaded first. this._super.apply(this, arguments); var deprecatedProperty, replacementProperty; var layoutSpecified = props.layoutName || props.layout || _emberMetalProperty_get.get(this, 'layoutName'); if (props.templateName && !layoutSpecified) { deprecatedProperty = 'templateName'; replacementProperty = 'layoutName'; props.layoutName = props.templateName; delete props['templateName']; } if (props.template && !layoutSpecified) { deprecatedProperty = 'template'; replacementProperty = 'layout'; props.layout = props.template; delete props['template']; } _emberMetalCore["default"].deprecate('Do not specify ' + deprecatedProperty + ' on a Component, use ' + replacementProperty + ' instead.', !deprecatedProperty); } }); }); // Ember.deprecate enifed("ember-views/mixins/empty_view_support", ["exports", "ember-metal/mixin", "ember-views/views/view", "ember-metal/property_get", "ember-metal/property_set", "ember-metal/computed"], function (exports, _emberMetalMixin, _emberViewsViewsView, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalComputed) { /** @class EmptyViewSupport @namespace Ember @private */ exports["default"] = _emberMetalMixin.Mixin.create({ /** This provides metadata about what kind of empty view class this collection would like if it is being instantiated from another system (like Handlebars) @private @property emptyViewClass */ emptyViewClass: _emberViewsViewsView["default"], /** An optional view to display if content is set to an empty array. @property emptyView @type Ember.View @default null @private */ emptyView: null, _emptyView: _emberMetalComputed.computed("emptyView", "attrs.emptyViewClass", "emptyViewClass", function () { var emptyView = _emberMetalProperty_get.get(this, "emptyView"); var attrsEmptyViewClass = this.getAttr("emptyViewClass"); var emptyViewClass = _emberMetalProperty_get.get(this, "emptyViewClass"); var inverse = _emberMetalProperty_get.get(this, "_itemViewInverse"); var actualEmpty = emptyView || attrsEmptyViewClass; // Somehow, our previous semantics differed depending on whether the // `emptyViewClass` was provided on the JavaScript class or via the // Handlebars template. // In Glimmer, we disambiguate between the two by checking first (and // preferring) the attrs-supplied class. // If not present, we fall back to the class's `emptyViewClass`, but only // if an inverse has been provided via an `{{else}}`. if (inverse && actualEmpty) { if (actualEmpty.extend) { return actualEmpty.extend({ template: inverse }); } else { _emberMetalProperty_set.set(actualEmpty, "template", inverse); } } else if (inverse && emptyViewClass) { return emptyViewClass.extend({ template: inverse }); } return actualEmpty; }) }); }); /** @module ember @submodule ember-views */ enifed("ember-views/mixins/instrumentation_support", ["exports", "ember-metal/mixin", "ember-metal/computed", "ember-metal/property_get"], function (exports, _emberMetalMixin, _emberMetalComputed, _emberMetalProperty_get) { /** @class InstrumentationSupport @namespace Ember @public */ var InstrumentationSupport = _emberMetalMixin.Mixin.create({ /** Used to identify this view during debugging @property instrumentDisplay @type String @public */ instrumentDisplay: _emberMetalComputed.computed(function () { if (this.helperName) { return "{{" + this.helperName + "}}"; } }), instrumentName: "view", instrumentDetails: function (hash) { hash.template = _emberMetalProperty_get.get(this, "templateName"); this._super(hash); } }); exports["default"] = InstrumentationSupport; }); /** @module ember @submodule ember-views */ enifed("ember-views/mixins/legacy_view_support", ["exports", "ember-metal/core", "ember-metal/mixin", "ember-metal/property_get"], function (exports, _emberMetalCore, _emberMetalMixin, _emberMetalProperty_get) { /** @class LegacyViewSupport @namespace Ember @private */ var LegacyViewSupport = _emberMetalMixin.Mixin.create({ beforeRender: function (buffer) {}, afterRender: function (buffer) {}, walkChildViews: function (callback) { var childViews = this.childViews.slice(); while (childViews.length) { var view = childViews.pop(); callback(view); childViews.push.apply(childViews, view.childViews); } }, mutateChildViews: function (callback) { var childViews = _emberMetalProperty_get.get(this, "childViews"); var idx = childViews.length; var view; while (--idx >= 0) { view = childViews[idx]; callback(this, view, idx); } return this; }, /** Removes all children from the `parentView`. @method removeAllChildren @return {Ember.View} receiver @private */ removeAllChildren: function () { return this.mutateChildViews(function (parentView, view) { parentView.removeChild(view); }); }, destroyAllChildren: function () { return this.mutateChildViews(function (parentView, view) { view.destroy(); }); }, /** Return the nearest ancestor whose parent is an instance of `klass`. @method nearestChildOf @param {Class} klass Subclass of Ember.View (or Ember.View itself) @return Ember.View @deprecated @private */ nearestChildOf: function (klass) { _emberMetalCore["default"].deprecate("nearestChildOf has been deprecated."); var view = _emberMetalProperty_get.get(this, "parentView"); while (view) { if (_emberMetalProperty_get.get(view, "parentView") instanceof klass) { return view; } view = _emberMetalProperty_get.get(view, "parentView"); } }, /** Return the nearest ancestor that is an instance of the provided class. @method nearestInstanceOf @param {Class} klass Subclass of Ember.View (or Ember.View itself) @return Ember.View @deprecated @private */ nearestInstanceOf: function (klass) { _emberMetalCore["default"].deprecate("nearestInstanceOf is deprecated and will be removed from future releases. Use nearestOfType."); var view = _emberMetalProperty_get.get(this, "parentView"); while (view) { if (view instanceof klass) { return view; } view = _emberMetalProperty_get.get(view, "parentView"); } } }); exports["default"] = LegacyViewSupport; }); /** @module ember @submodule ember-views */ enifed("ember-views/mixins/normalized_rerender_if_needed", ["exports", "ember-metal/property_get", "ember-metal/mixin", "ember-metal/merge", "ember-views/views/states"], function (exports, _emberMetalProperty_get, _emberMetalMixin, _emberMetalMerge, _emberViewsViewsStates) { var states = _emberViewsViewsStates.cloneStates(_emberViewsViewsStates.states); _emberMetalMerge["default"](states._default, { rerenderIfNeeded: function () { return this; } }); _emberMetalMerge["default"](states.inDOM, { rerenderIfNeeded: function (view) { if (view.normalizedValue() !== view._lastNormalizedValue) { view.rerender(); } } }); exports["default"] = _emberMetalMixin.Mixin.create({ _states: states, normalizedValue: function () { var value = this.lazyValue.value(); var valueNormalizer = _emberMetalProperty_get.get(this, "valueNormalizerFunc"); return valueNormalizer ? valueNormalizer(value) : value; }, rerenderIfNeeded: function () { this.currentState.rerenderIfNeeded(this); } }); }); /** @module ember @submodule ember-views */ enifed("ember-views/mixins/template_rendering_support", ["exports", "ember-metal/mixin"], function (exports, _emberMetalMixin) { // Circular dep var _renderView; /** @class TemplateRenderingSupport @namespace Ember @private */ var TemplateRenderingSupport = _emberMetalMixin.Mixin.create({ /** Called on your view when it should push strings of HTML into a `Ember.RenderBuffer`. Most users will want to override the `template` or `templateName` properties instead of this method. By default, `Ember.View` will look for a function in the `template` property and invoke it with the value of `context`. The value of `context` will be the view's controller unless you override it. @method renderBlock @param {Ember.RenderBuffer} buffer The render buffer @private */ renderBlock: function (block, renderNode) { if (_renderView === undefined) { _renderView = eriuqer("ember-htmlbars/system/render-view"); } return _renderView.renderHTMLBarsBlock(this, block, renderNode); } }); exports["default"] = TemplateRenderingSupport; }); /** @module ember @submodule ember-views */ enifed("ember-views/mixins/text_support", ["exports", "ember-metal/property_get", "ember-metal/property_set", "ember-metal/mixin", "ember-runtime/mixins/target_action_support"], function (exports, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalMixin, _emberRuntimeMixinsTarget_action_support) { /** `TextSupport` is a shared mixin used by both `Ember.TextField` and `Ember.TextArea`. `TextSupport` adds a number of methods that allow you to specify a controller action to invoke when a certain event is fired on your text field or textarea. The specifed controller action would get the current value of the field passed in as the only argument unless the value of the field is empty. In that case, the instance of the field itself is passed in as the only argument. Let's use the pressing of the escape key as an example. If you wanted to invoke a controller action when a user presses the escape key while on your field, you would use the `escape-press` attribute on your field like so: ```handlebars {{! application.hbs}} {{input escape-press='alertUser'}} ``` ```javascript App = Ember.Application.create(); App.ApplicationController = Ember.Controller.extend({ actions: { alertUser: function ( currentValue ) { alert( 'escape pressed, current value: ' + currentValue ); } } }); ``` The following chart is a visual representation of what takes place when the escape key is pressed in this scenario: ``` The Template +---------------------------+ | | | escape-press='alertUser' | | | TextSupport Mixin +----+----------------------+ +-------------------------------+ | | cancel method | | escape button pressed | | +-------------------------------> | checks for the `escape-press` | | attribute and pulls out the | +-------------------------------+ | `alertUser` value | | action name 'alertUser' +-------------------------------+ | sent to controller v Controller +------------------------------------------ + | | | actions: { | | alertUser: function( currentValue ){ | | alert( 'the esc key was pressed!' ) | | } | | } | | | +-------------------------------------------+ ``` Here are the events that we currently support along with the name of the attribute you would need to use on your field. To reiterate, you would use the attribute name like so: ```handlebars {{input attribute-name='controllerAction'}} ``` ``` +--------------------+----------------+ | | | | event | attribute name | +--------------------+----------------+ | new line inserted | insert-newline | | | | | enter key pressed | insert-newline | | | | | cancel key pressed | escape-press | | | | | focusin | focus-in | | | | | focusout | focus-out | | | | | keypress | key-press | | | | | keyup | key-up | | | | | keydown | key-down | +--------------------+----------------+ ``` @class TextSupport @namespace Ember @uses Ember.TargetActionSupport @extends Ember.Mixin @private */ var TextSupport = _emberMetalMixin.Mixin.create(_emberRuntimeMixinsTarget_action_support["default"], { value: "", attributeBindings: ["autocapitalize", "autocorrect", "autofocus", "disabled", "form", "maxlength", "placeholder", "readonly", "required", "selectionDirection", "spellcheck", "tabindex", "title"], placeholder: null, disabled: false, maxlength: null, init: function () { this._super.apply(this, arguments); this.on("paste", this, this._elementValueDidChange); this.on("cut", this, this._elementValueDidChange); this.on("input", this, this._elementValueDidChange); }, /** The action to be sent when the user presses the return key. This is similar to the `{{action}}` helper, but is fired when the user presses the return key when editing a text field, and sends the value of the field as the context. @property action @type String @default null @private */ action: null, /** The event that should send the action. Options are: * `enter`: the user pressed enter * `keyPress`: the user pressed a key @property onEvent @type String @default enter @private */ onEvent: "enter", /** Whether the `keyUp` event that triggers an `action` to be sent continues propagating to other views. By default, when the user presses the return key on their keyboard and the text field has an `action` set, the action will be sent to the view's controller and the key event will stop propagating. If you would like parent views to receive the `keyUp` event even after an action has been dispatched, set `bubbles` to true. @property bubbles @type Boolean @default false @private */ bubbles: false, interpretKeyEvents: function (event) { var map = TextSupport.KEY_EVENTS; var method = map[event.keyCode]; this._elementValueDidChange(); if (method) { return this[method](event); } }, _elementValueDidChange: function () { // Using readDOMAttr will ensure that HTMLBars knows the last // value. _emberMetalProperty_set.set(this, "value", this.readDOMAttr("value")); }, change: function (event) { this._elementValueDidChange(event); }, /** Allows you to specify a controller action to invoke when either the `enter` key is pressed or, in the case of the field being a textarea, when a newline is inserted. To use this method, give your field an `insert-newline` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `insert-newline` attribute, please reference the example near the top of this file. @method insertNewline @param {Event} event @private */ insertNewline: function (event) { sendAction("enter", this, event); sendAction("insert-newline", this, event); }, /** Allows you to specify a controller action to invoke when the escape button is pressed. To use this method, give your field an `escape-press` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `escape-press` attribute, please reference the example near the top of this file. @method cancel @param {Event} event @private */ cancel: function (event) { sendAction("escape-press", this, event); }, /** Allows you to specify a controller action to invoke when a field receives focus. To use this method, give your field a `focus-in` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `focus-in` attribute, please reference the example near the top of this file. @method focusIn @param {Event} event @private */ focusIn: function (event) { sendAction("focus-in", this, event); }, /** Allows you to specify a controller action to invoke when a field loses focus. To use this method, give your field a `focus-out` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `focus-out` attribute, please reference the example near the top of this file. @method focusOut @param {Event} event @private */ focusOut: function (event) { this._elementValueDidChange(event); sendAction("focus-out", this, event); }, /** Allows you to specify a controller action to invoke when a key is pressed. To use this method, give your field a `key-press` attribute. The value of that attribute should be the name of the action in your controller you that wish to invoke. For an example on how to use the `key-press` attribute, please reference the example near the top of this file. @method keyPress @param {Event} event @private */ keyPress: function (event) { sendAction("key-press", this, event); }, /** Allows you to specify a controller action to invoke when a key-up event is fired. To use this method, give your field a `key-up` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `key-up` attribute, please reference the example near the top of this file. @method keyUp @param {Event} event @private */ keyUp: function (event) { this.interpretKeyEvents(event); this.sendAction("key-up", _emberMetalProperty_get.get(this, "value"), event); }, /** Allows you to specify a controller action to invoke when a key-down event is fired. To use this method, give your field a `key-down` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `key-down` attribute, please reference the example near the top of this file. @method keyDown @param {Event} event @private */ keyDown: function (event) { this.sendAction("key-down", _emberMetalProperty_get.get(this, "value"), event); } }); TextSupport.KEY_EVENTS = { 13: "insertNewline", 27: "cancel" }; // In principle, this shouldn't be necessary, but the legacy // sendAction semantics for TextField are different from // the component semantics so this method normalizes them. function sendAction(eventName, view, event) { var action = _emberMetalProperty_get.get(view, "attrs." + eventName) || _emberMetalProperty_get.get(view, eventName); var on = _emberMetalProperty_get.get(view, "onEvent"); var value = _emberMetalProperty_get.get(view, "value"); // back-compat support for keyPress as an event name even though // it's also a method name that consumes the event (and therefore // incompatible with sendAction semantics). if (on === eventName || on === "keyPress" && eventName === "key-press") { view.sendAction("action", value); } view.sendAction(eventName, value); if (action || on === eventName) { if (!_emberMetalProperty_get.get(view, "bubbles")) { event.stopPropagation(); } } } exports["default"] = TextSupport; }); /** @module ember @submodule ember-views */ enifed("ember-views/mixins/view_child_views_support", ["exports", "ember-metal/core", "ember-metal/mixin", "ember-metal/enumerable_utils", "ember-metal/property_get", "ember-metal/property_set", "ember-metal/set_properties"], function (exports, _emberMetalCore, _emberMetalMixin, _emberMetalEnumerable_utils, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalSet_properties) { var EMPTY_ARRAY = []; exports["default"] = _emberMetalMixin.Mixin.create({ /** Array of child views. You should never edit this array directly. Instead, use `appendChild` and `removeFromParent`. @property childViews @type Array @default [] @private */ childViews: EMPTY_ARRAY, init: function () { this._super.apply(this, arguments); // setup child views. be sure to clone the child views array first // 2.0TODO: Remove Ember.A() here this.childViews = _emberMetalCore["default"].A(this.childViews.slice()); this.ownerView = this.ownerView || this; }, appendChild: function (view) { this.linkChild(view); this.childViews.push(view); }, destroyChild: function (view) { view.destroy(); }, /** Removes the child view from the parent view. @method removeChild @param {Ember.View} view @return {Ember.View} receiver @private */ removeChild: function (view) { // If we're destroying, the entire subtree will be // freed, and the DOM will be handled separately, // so no need to mess with childViews. if (this.isDestroying) { return; } // update parent node this.unlinkChild(view); // remove view from childViews array. var childViews = _emberMetalProperty_get.get(this, "childViews"); _emberMetalEnumerable_utils.removeObject(childViews, view); return this; }, /** Instantiates a view to be added to the childViews array during view initialization. You generally will not call this method directly unless you are overriding `createChildViews()`. Note that this method will automatically configure the correct settings on the new view instance to act as a child of the parent. @method createChildView @param {Class|String} viewClass @param {Object} [attrs] Attributes to add @return {Ember.View} new instance @private */ createChildView: function (maybeViewClass, _attrs) { if (!maybeViewClass) { throw new TypeError("createChildViews first argument must exist"); } if (maybeViewClass.isView && maybeViewClass.parentView === this && maybeViewClass.container === this.container) { return maybeViewClass; } var attrs = _attrs || {}; var view; attrs.parentView = this; attrs.renderer = this.renderer; attrs._viewRegistry = this._viewRegistry; if (maybeViewClass.isViewFactory) { attrs.container = this.container; view = maybeViewClass.create(attrs); if (view.viewName) { _emberMetalProperty_set.set(this, view.viewName, view); } } else if ("string" === typeof maybeViewClass) { var fullName = "view:" + maybeViewClass; var ViewKlass = this.container.lookupFactory(fullName); _emberMetalCore["default"].assert("Could not find view: '" + fullName + "'", !!ViewKlass); view = ViewKlass.create(attrs); } else { view = maybeViewClass; _emberMetalCore["default"].assert("You must pass instance or subclass of View", view.isView); attrs.container = this.container; _emberMetalSet_properties["default"](view, attrs); } this.linkChild(view); return view; }, linkChild: function (instance) { instance.container = this.container; if (_emberMetalProperty_get.get(instance, "parentView") !== this) { // linkChild should be idempotentj _emberMetalProperty_set.set(instance, "parentView", this); instance.trigger("parentViewDidChange"); } instance.ownerView = this.ownerView; }, unlinkChild: function (instance) { _emberMetalProperty_set.set(instance, "parentView", null); instance.trigger("parentViewDidChange"); } }); }); /** @module ember @submodule ember-views */ enifed("ember-views/mixins/view_context_support", ["exports", "ember-metal/mixin", "ember-metal/computed", "ember-metal/property_get", "ember-metal/property_set", "ember-views/mixins/legacy_view_support", "ember-metal/events"], function (exports, _emberMetalMixin, _emberMetalComputed, _emberMetalProperty_get, _emberMetalProperty_set, _emberViewsMixinsLegacy_view_support, _emberMetalEvents) { var ViewContextSupport = _emberMetalMixin.Mixin.create(_emberViewsMixinsLegacy_view_support["default"], { /** The object from which templates should access properties. This object will be passed to the template function each time the render method is called, but it is up to the individual function to decide what to do with it. By default, this will be the view's controller. @property context @type Object @private */ context: _emberMetalComputed.computed({ get: function () { return _emberMetalProperty_get.get(this, "_context"); }, set: function (key, value) { _emberMetalProperty_set.set(this, "_context", value); return value; } })["volatile"](), /** Private copy of the view's template context. This can be set directly by Handlebars without triggering the observer that causes the view to be re-rendered. The context of a view is looked up as follows: 1. Supplied context (usually by Handlebars) 2. Specified controller 3. `parentView`'s context (for a child of a ContainerView) The code in Handlebars that overrides the `_context` property first checks to see whether the view has a specified controller. This is something of a hack and should be revisited. @property _context @private */ _context: _emberMetalComputed.computed({ get: function () { var parentView, controller; if (controller = _emberMetalProperty_get.get(this, "controller")) { return controller; } parentView = this.parentView; if (parentView) { return _emberMetalProperty_get.get(parentView, "_context"); } return null; }, set: function (key, value) { return value; } }), _controller: null, /** The controller managing this view. If this property is set, it will be made available for use by the template. @property controller @type Object @private */ controller: _emberMetalComputed.computed({ get: function () { if (this._controller) { return this._controller; } return this.parentView ? _emberMetalProperty_get.get(this.parentView, "controller") : null; }, set: function (_, value) { this._controller = value; return value; } }), _legacyControllerDidChange: _emberMetalMixin.observer("controller", function () { this.walkChildViews(function (view) { return view.notifyPropertyChange("controller"); }); }), _notifyControllerChange: _emberMetalEvents.on("parentViewDidChange", function () { this.notifyPropertyChange("controller"); }) }); exports["default"] = ViewContextSupport; }); /** @module ember @submodule ember-views */ enifed("ember-views/mixins/view_state_support", ["exports", "ember-metal/core", "ember-metal/mixin"], function (exports, _emberMetalCore, _emberMetalMixin) { var ViewStateSupport = _emberMetalMixin.Mixin.create({ transitionTo: function (state) { _emberMetalCore["default"].deprecate("Ember.View#transitionTo has been deprecated, it is for internal use only"); this._transitionTo(state); }, _transitionTo: function (state) { var priorState = this.currentState; var currentState = this.currentState = this._states[state]; this._state = state; if (priorState && priorState.exit) { priorState.exit(this); } if (currentState.enter) { currentState.enter(this); } } }); exports["default"] = ViewStateSupport; }); enifed("ember-views/mixins/view_target_action_support", ["exports", "ember-metal/mixin", "ember-runtime/mixins/target_action_support", "ember-metal/alias"], function (exports, _emberMetalMixin, _emberRuntimeMixinsTarget_action_support, _emberMetalAlias) { /** `Ember.ViewTargetActionSupport` is a mixin that can be included in a view class to add a `triggerAction` method with semantics similar to the Handlebars `{{action}}` helper. It provides intelligent defaults for the action's target: the view's controller; and the context that is sent with the action: the view's context. Note: In normal Ember usage, the `{{action}}` helper is usually the best choice. This mixin is most often useful when you are doing more complex event handling in custom View subclasses. For example: ```javascript App.SaveButtonView = Ember.View.extend(Ember.ViewTargetActionSupport, { action: 'save', click: function() { this.triggerAction(); // Sends the `save` action, along with the current context // to the current controller } }); ``` The `action` can be provided as properties of an optional object argument to `triggerAction` as well. ```javascript App.SaveButtonView = Ember.View.extend(Ember.ViewTargetActionSupport, { click: function() { this.triggerAction({ action: 'save' }); // Sends the `save` action, along with the current context // to the current controller } }); ``` @class ViewTargetActionSupport @namespace Ember @extends Ember.TargetActionSupport @private */ exports["default"] = _emberMetalMixin.Mixin.create(_emberRuntimeMixinsTarget_action_support["default"], { /** @property target @private */ target: _emberMetalAlias["default"]("controller"), /** @property actionContext @private */ actionContext: _emberMetalAlias["default"]("context") }); }); enifed("ember-views/mixins/visibility_support", ["exports", "ember-metal/mixin", "ember-metal/property_get", "ember-metal/run_loop"], function (exports, _emberMetalMixin, _emberMetalProperty_get, _emberMetalRun_loop) { function K() { return this; } /** @class VisibilitySupport @namespace Ember @public */ var VisibilitySupport = _emberMetalMixin.Mixin.create({ /** If `false`, the view will appear hidden in DOM. @property isVisible @type Boolean @default null @public */ isVisible: true, becameVisible: K, becameHidden: K, /** When the view's `isVisible` property changes, toggle the visibility element of the actual DOM element. @method _isVisibleDidChange @private */ _isVisibleDidChange: _emberMetalMixin.observer("isVisible", function () { if (this._isVisible === _emberMetalProperty_get.get(this, "isVisible")) { return; } _emberMetalRun_loop["default"].scheduleOnce("render", this, this._toggleVisibility); }), _toggleVisibility: function () { var $el = this.$(); var isVisible = _emberMetalProperty_get.get(this, "isVisible"); if (this._isVisible === isVisible) { return; } // It's important to keep these in sync, even if we don't yet have // an element in the DOM to manipulate: this._isVisible = isVisible; if (!$el) { return; } $el.toggle(isVisible); if (this._isAncestorHidden()) { return; } if (isVisible) { this._notifyBecameVisible(); } else { this._notifyBecameHidden(); } }, _notifyBecameVisible: function () { this.trigger("becameVisible"); this.forEachChildView(function (view) { var isVisible = _emberMetalProperty_get.get(view, "isVisible"); if (isVisible || isVisible === null) { view._notifyBecameVisible(); } }); }, _notifyBecameHidden: function () { this.trigger("becameHidden"); this.forEachChildView(function (view) { var isVisible = _emberMetalProperty_get.get(view, "isVisible"); if (isVisible || isVisible === null) { view._notifyBecameHidden(); } }); }, _isAncestorHidden: function () { var parent = _emberMetalProperty_get.get(this, "parentView"); while (parent) { if (_emberMetalProperty_get.get(parent, "isVisible") === false) { return true; } parent = _emberMetalProperty_get.get(parent, "parentView"); } return false; } }); exports["default"] = VisibilitySupport; }); /** @module ember @submodule ember-views */ enifed("ember-views/streams/class_name_binding", ["exports", "ember-metal/streams/utils", "ember-metal/property_get", "ember-runtime/system/string", "ember-metal/utils"], function (exports, _emberMetalStreamsUtils, _emberMetalProperty_get, _emberRuntimeSystemString, _emberMetalUtils) { exports.parsePropertyPath = parsePropertyPath; exports.classStringForValue = classStringForValue; exports.streamifyClassNameBinding = streamifyClassNameBinding; /** Parse a path and return an object which holds the parsed properties. For example a path like "content.isEnabled:enabled:disabled" will return the following object: ```javascript { path: "content.isEnabled", className: "enabled", falsyClassName: "disabled", classNames: ":enabled:disabled" } ``` @method parsePropertyPath @static @private */ function parsePropertyPath(path) { var split = path.split(":"); var propertyPath = split[0]; var classNames = ""; var className, falsyClassName; // check if the property is defined as prop:class or prop:trueClass:falseClass if (split.length > 1) { className = split[1]; if (split.length === 3) { falsyClassName = split[2]; } classNames = ":" + className; if (falsyClassName) { classNames += ":" + falsyClassName; } } return { path: propertyPath, classNames: classNames, className: className === "" ? undefined : className, falsyClassName: falsyClassName }; } /** Get the class name for a given value, based on the path, optional `className` and optional `falsyClassName`. - if a `className` or `falsyClassName` has been specified: - if the value is truthy and `className` has been specified, `className` is returned - if the value is falsy and `falsyClassName` has been specified, `falsyClassName` is returned - otherwise `null` is returned - if the value is `true`, the dasherized last part of the supplied path is returned - if the value is not `false`, `undefined` or `null`, the `value` is returned - if none of the above rules apply, `null` is returned @method classStringForValue @param path @param val @param className @param falsyClassName @static @private */ function classStringForValue(path, val, className, falsyClassName) { if (_emberMetalUtils.isArray(val)) { val = _emberMetalProperty_get.get(val, "length") !== 0; } // When using the colon syntax, evaluate the truthiness or falsiness // of the value to determine which className to return if (className || falsyClassName) { if (className && !!val) { return className; } else if (falsyClassName && !val) { return falsyClassName; } else { return null; } // If value is a Boolean and true, return the dasherized property // name. } else if (val === true) { // Normalize property path to be suitable for use // as a class name. For exaple, content.foo.barBaz // becomes bar-baz. var parts = path.split("."); return _emberRuntimeSystemString.dasherize(parts[parts.length - 1]); // If the value is not false, undefined, or null, return the current // value of the property. } else if (val !== false && val != null) { return val; // Nothing to display. Return null so that the old class is removed // but no new class is added. } else { return null; } } function streamifyClassNameBinding(view, classNameBinding, prefix) { prefix = prefix || ""; Ember.assert("classNameBindings must not have spaces in them. Multiple class name bindings can be provided as elements of an array, e.g. ['foo', ':bar']", classNameBinding.indexOf(" ") === -1); var parsedPath = parsePropertyPath(classNameBinding); if (parsedPath.path === "") { return classStringForValue(parsedPath.path, true, parsedPath.className, parsedPath.falsyClassName); } else { var pathValue = view.getStream(prefix + parsedPath.path); return _emberMetalStreamsUtils.chain(pathValue, function () { return classStringForValue(parsedPath.path, _emberMetalStreamsUtils.read(pathValue), parsedPath.className, parsedPath.falsyClassName); }); } } }); enifed("ember-views/streams/should_display", ["exports", "ember-metal/platform/create", "ember-metal/merge", "ember-metal/property_get", "ember-runtime/utils", "ember-metal/streams/stream", "ember-metal/streams/utils"], function (exports, _emberMetalPlatformCreate, _emberMetalMerge, _emberMetalProperty_get, _emberRuntimeUtils, _emberMetalStreamsStream, _emberMetalStreamsUtils) { exports["default"] = shouldDisplay; function shouldDisplay(predicate) { if (_emberMetalStreamsUtils.isStream(predicate)) { return new ShouldDisplayStream(predicate); } var truthy = predicate && _emberMetalProperty_get.get(predicate, "isTruthy"); if (typeof truthy === "boolean") { return truthy; } if (_emberRuntimeUtils.isArray(predicate)) { return _emberMetalProperty_get.get(predicate, "length") !== 0; } else { return !!predicate; } } function ShouldDisplayStream(predicate) { Ember.assert("ShouldDisplayStream error: predicate must be a stream", _emberMetalStreamsUtils.isStream(predicate)); var isTruthy = predicate.get("isTruthy"); this.init(); this.predicate = predicate; this.isTruthy = isTruthy; this.lengthDep = null; this.addDependency(predicate); this.addDependency(isTruthy); } ShouldDisplayStream.prototype = _emberMetalPlatformCreate["default"](_emberMetalStreamsStream["default"].prototype); _emberMetalMerge["default"](ShouldDisplayStream.prototype, { compute: function () { var truthy = _emberMetalStreamsUtils.read(this.isTruthy); if (typeof truthy === "boolean") { return truthy; } if (this.lengthDep) { return this.lengthDep.getValue() !== 0; } else { return !!_emberMetalStreamsUtils.read(this.predicate); } }, revalidate: function () { if (_emberRuntimeUtils.isArray(_emberMetalStreamsUtils.read(this.predicate))) { if (!this.lengthDep) { this.lengthDep = this.addMutableDependency(this.predicate.get("length")); } } else { if (this.lengthDep) { this.lengthDep.destroy(); this.lengthDep = null; } } } }); }); enifed("ember-views/streams/utils", ["exports", "ember-metal/core", "ember-metal/property_get", "ember-metal/path_cache", "ember-runtime/system/string", "ember-metal/streams/utils", "ember-runtime/mixins/controller"], function (exports, _emberMetalCore, _emberMetalProperty_get, _emberMetalPath_cache, _emberRuntimeSystemString, _emberMetalStreamsUtils, _emberRuntimeMixinsController) { exports.readViewFactory = readViewFactory; exports.readComponentFactory = readComponentFactory; exports.readUnwrappedModel = readUnwrappedModel; function readViewFactory(object, container) { var value = _emberMetalStreamsUtils.read(object); var viewClass; if (typeof value === "string") { if (_emberMetalPath_cache.isGlobal(value)) { viewClass = _emberMetalProperty_get.get(null, value); _emberMetalCore["default"].deprecate("Resolved the view \"" + value + "\" on the global context. Pass a view name to be looked up on the container instead, such as {{view \"select\"}}.", !viewClass, { url: "http://emberjs.com/guides/deprecations/#toc_global-lookup-of-views" }); } else { _emberMetalCore["default"].assert("View requires a container to resolve views not passed in through the context", !!container); viewClass = container.lookupFactory("view:" + value); } } else { viewClass = value; } _emberMetalCore["default"].assert(_emberRuntimeSystemString.fmt(value + " must be a subclass or an instance of Ember.View, not %@", [viewClass]), (function (viewClass) { return viewClass && (viewClass.isViewFactory || viewClass.isView || viewClass.isComponentFactory || viewClass.isComponent); })(viewClass)); return viewClass; } function readComponentFactory(nameOrStream, container) { var name = _emberMetalStreamsUtils.read(nameOrStream); var componentLookup = container.lookup("component-lookup:main"); _emberMetalCore["default"].assert("Could not find 'component-lookup:main' on the provided container," + " which is necessary for performing component lookups", componentLookup); return componentLookup.lookupFactory(name, container); } function readUnwrappedModel(object) { if (_emberMetalStreamsUtils.isStream(object)) { var result = object.value(); // If the path is exactly `controller` then we don't unwrap it. if (object.label !== "controller") { while (_emberRuntimeMixinsController["default"].detect(result)) { result = _emberMetalProperty_get.get(result, "model"); } } return result; } else { return object; } } }); enifed("ember-views/system/action_manager", ["exports"], function (exports) { /** @module ember @submodule ember-views */ function ActionManager() {} /** Global action id hash. @private @property registeredActions @type Object */ ActionManager.registeredActions = {}; exports["default"] = ActionManager; }); enifed("ember-views/system/build-component-template", ["exports", "htmlbars-runtime", "ember-htmlbars/hooks/get-value", "ember-metal/property_get", "ember-metal/path_cache"], function (exports, _htmlbarsRuntime, _emberHtmlbarsHooksGetValue, _emberMetalProperty_get, _emberMetalPath_cache) { exports["default"] = buildComponentTemplate; function buildComponentTemplate(_ref, attrs, content) { var component = _ref.component; var layout = _ref.layout; var isAngleBracket = _ref.isAngleBracket; var blockToRender, tagName, meta; if (component === undefined) { component = null; } if (layout && layout.raw) { var yieldTo = createContentBlocks(content.templates, content.scope, content.self, component); blockToRender = createLayoutBlock(layout.raw, yieldTo, content.self, component, attrs); meta = layout.raw.meta; } else if (content.templates && content.templates["default"]) { blockToRender = createContentBlock(content.templates["default"], content.scope, content.self, component); meta = content.templates["default"].meta; } if (component) { tagName = tagNameFor(component); // If this is not a tagless component, we need to create the wrapping // element. We use `manualElement` to create a template that represents // the wrapping element and yields to the previous block. if (tagName !== "") { var attributes = normalizeComponentAttributes(component, isAngleBracket, attrs); var elementTemplate = _htmlbarsRuntime.internal.manualElement(tagName, attributes); elementTemplate.meta = meta; blockToRender = createElementBlock(elementTemplate, blockToRender, component); } else { validateTaglessComponent(component); } } // tagName is one of: // * `undefined` if no component is present // * the falsy value "" if set explicitly on the component // * an actual tagName set explicitly on the component return { createdElement: !!tagName, block: blockToRender }; } function blockFor(template, options) { Ember.assert("BUG: Must pass a template to blockFor", !!template); return _htmlbarsRuntime.internal.blockFor(_htmlbarsRuntime.render, template, options); } function createContentBlock(template, scope, self, component) { Ember.assert("BUG: buildComponentTemplate can take a scope or a self, but not both", !(scope && self)); return blockFor(template, { scope: scope, self: self, options: { view: component } }); } function createContentBlocks(templates, scope, self, component) { if (!templates) { return; } var output = {}; for (var name in templates) { if (templates.hasOwnProperty(name)) { var template = templates[name]; if (template) { output[name] = createContentBlock(templates[name], scope, self, component); } } } return output; } function createLayoutBlock(template, yieldTo, self, component, attrs) { return blockFor(template, { yieldTo: yieldTo, // If we have an old-style Controller with a template it will be // passed as our `self` argument, and it should be the context for // the template. Otherwise, we must have a real Component and it // should be its own template context. self: self || component, options: { view: component, attrs: attrs } }); } function createElementBlock(template, yieldTo, component) { return blockFor(template, { yieldTo: yieldTo, self: component, options: { view: component } }); } function tagNameFor(view) { var tagName = view.tagName; if (tagName !== null && typeof tagName === "object" && tagName.isDescriptor) { tagName = _emberMetalProperty_get.get(view, "tagName"); Ember.deprecate("In the future using a computed property to define tagName will not be permitted. That value will be respected, but changing it will not update the element.", !tagName); } if (tagName === null || tagName === undefined) { tagName = view._defaultTagName || "div"; } return tagName; } // Takes a component and builds a normalized set of attribute // bindings consumable by HTMLBars' `attribute` hook. function normalizeComponentAttributes(component, isAngleBracket, attrs) { var normalized = {}; var attributeBindings = component.attributeBindings; var i, l; if (attributeBindings) { for (i = 0, l = attributeBindings.length; i < l; i++) { var attr = attributeBindings[i]; var colonIndex = attr.indexOf(":"); var attrName, expression; if (colonIndex !== -1) { var attrProperty = attr.substring(0, colonIndex); attrName = attr.substring(colonIndex + 1); expression = ["get", "view." + attrProperty]; } else if (attrs[attr]) { // TODO: For compatibility with 1.x, we probably need to `set` // the component's attribute here if it is a CP, but we also // probably want to suspend observers and allow the // willUpdateAttrs logic to trigger observers at the correct time. attrName = attr; expression = ["value", attrs[attr]]; } else { attrName = attr; expression = ["get", "view." + attr]; } Ember.assert("You cannot use class as an attributeBinding, use classNameBindings instead.", attrName !== "class"); normalized[attrName] = expression; } } if (isAngleBracket) { for (var prop in attrs) { var val = attrs[prop]; if (!val) { continue; } if (typeof val === "string" || val.isConcat) { normalized[prop] = ["value", val]; } } } if (attrs.id && _emberHtmlbarsHooksGetValue["default"](attrs.id)) { // Do not allow binding to the `id` normalized.id = _emberHtmlbarsHooksGetValue["default"](attrs.id); component.elementId = normalized.id; } else { normalized.id = component.elementId; } if (attrs.tagName) { component.tagName = attrs.tagName; } var normalizedClass = normalizeClass(component, attrs); if (normalizedClass) { normalized["class"] = normalizedClass; } if (_emberMetalProperty_get.get(component, "isVisible") === false) { var hiddenStyle = ["subexpr", "-html-safe", ["display: none;"], []]; var existingStyle = normalized.style; if (existingStyle) { normalized.style = ["subexpr", "concat", [existingStyle, " ", hiddenStyle], []]; } else { normalized.style = hiddenStyle; } } return normalized; } function normalizeClass(component, attrs) { var i, l; var normalizedClass = []; var classNames = _emberMetalProperty_get.get(component, "classNames"); var classNameBindings = _emberMetalProperty_get.get(component, "classNameBindings"); if (attrs["class"]) { if (typeof attrs["class"] === "string") { normalizedClass.push(attrs["class"]); } else { normalizedClass.push(["subexpr", "-normalize-class", [["value", attrs["class"].path], ["value", attrs["class"]]], []]); } } if (attrs.classBinding) { normalizeClasses(attrs.classBinding.split(" "), normalizedClass); } if (attrs.classNames) { normalizedClass.push(["value", attrs.classNames]); } if (classNames) { for (i = 0, l = classNames.length; i < l; i++) { normalizedClass.push(classNames[i]); } } if (classNameBindings) { normalizeClasses(classNameBindings, normalizedClass); } if (normalizeClass.length) { return ["subexpr", "-join-classes", normalizedClass, []]; } } function normalizeClasses(classes, output) { var i, l; for (i = 0, l = classes.length; i < l; i++) { var className = classes[i]; Ember.assert("classNameBindings must not have spaces in them. Multiple class name bindings can be provided as elements of an array, e.g. ['foo', ':bar']", className.indexOf(" ") === -1); var _className$split = className.split(":"); var propName = _className$split[0]; var activeClass = _className$split[1]; var inactiveClass = _className$split[2]; // Legacy :class microsyntax for static class names if (propName === "") { output.push(activeClass); continue; } // 2.0TODO: Remove deprecated global path var prop = _emberMetalPath_cache.isGlobal(propName) ? propName : "view." + propName; output.push(["subexpr", "-normalize-class", [ // params ["value", propName], ["get", prop]], [ // hash "activeClass", activeClass, "inactiveClass", inactiveClass]]); } } function validateTaglessComponent(component) { Ember.assert("You cannot use `classNameBindings` on a tag-less component: " + component.toString(), function () { var classNameBindings = component.classNameBindings; return !classNameBindings || classNameBindings.length === 0; }); } }); enifed("ember-views/system/event_dispatcher", ["exports", "ember-metal/core", "ember-metal/property_get", "ember-metal/property_set", "ember-metal/is_none", "ember-metal/run_loop", "ember-runtime/system/string", "ember-runtime/system/object", "ember-views/system/jquery", "ember-views/system/action_manager", "ember-views/views/view", "ember-metal/merge"], function (exports, _emberMetalCore, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalIs_none, _emberMetalRun_loop, _emberRuntimeSystemString, _emberRuntimeSystemObject, _emberViewsSystemJquery, _emberViewsSystemAction_manager, _emberViewsViewsView, _emberMetalMerge) { /** `Ember.EventDispatcher` handles delegating browser events to their corresponding `Ember.Views.` For example, when you click on a view, `Ember.EventDispatcher` ensures that that view's `mouseDown` method gets called. @class EventDispatcher @namespace Ember @private @extends Ember.Object */ exports["default"] = _emberRuntimeSystemObject["default"].extend({ /** The set of events names (and associated handler function names) to be setup and dispatched by the `EventDispatcher`. Custom events can added to this list at setup time, generally via the `Ember.Application.customEvents` hash. Only override this default set to prevent the EventDispatcher from listening on some events all together. This set will be modified by `setup` to also include any events added at that time. @property events @type Object @private */ events: { touchstart: "touchStart", touchmove: "touchMove", touchend: "touchEnd", touchcancel: "touchCancel", keydown: "keyDown", keyup: "keyUp", keypress: "keyPress", mousedown: "mouseDown", mouseup: "mouseUp", contextmenu: "contextMenu", click: "click", dblclick: "doubleClick", mousemove: "mouseMove", focusin: "focusIn", focusout: "focusOut", mouseenter: "mouseEnter", mouseleave: "mouseLeave", submit: "submit", input: "input", change: "change", dragstart: "dragStart", drag: "drag", dragenter: "dragEnter", dragleave: "dragLeave", dragover: "dragOver", drop: "drop", dragend: "dragEnd" }, /** The root DOM element to which event listeners should be attached. Event listeners will be attached to the document unless this is overridden. Can be specified as a DOMElement or a selector string. The default body is a string since this may be evaluated before document.body exists in the DOM. @private @property rootElement @type DOMElement @default 'body' */ rootElement: "body", /** It enables events to be dispatched to the view's `eventManager.` When present, this object takes precedence over handling of events on the view itself. Note that most Ember applications do not use this feature. If your app also does not use it, consider setting this property to false to gain some performance improvement by allowing the EventDispatcher to skip the search for the `eventManager` on the view tree. ```javascript var EventDispatcher = Em.EventDispatcher.extend({ events: { click : 'click', focusin : 'focusIn', focusout : 'focusOut', change : 'change' }, canDispatchToEventManager: false }); container.register('event_dispatcher:main', EventDispatcher); ``` @property canDispatchToEventManager @type boolean @default 'true' @since 1.7.0 @private */ canDispatchToEventManager: true, /** Sets up event listeners for standard browser events. This will be called after the browser sends a `DOMContentReady` event. By default, it will set up all of the listeners on the document body. If you would like to register the listeners on a different element, set the event dispatcher's `root` property. @private @method setup @param addedEvents {Object} */ setup: function (addedEvents, rootElement) { var event; var events = _emberMetalProperty_get.get(this, "events"); _emberMetalMerge["default"](events, addedEvents || {}); if (!_emberMetalIs_none["default"](rootElement)) { _emberMetalProperty_set.set(this, "rootElement", rootElement); } rootElement = _emberViewsSystemJquery["default"](_emberMetalProperty_get.get(this, "rootElement")); _emberMetalCore["default"].assert(_emberRuntimeSystemString.fmt("You cannot use the same root element (%@) multiple times in an Ember.Application", [rootElement.selector || rootElement[0].tagName]), !rootElement.is(".ember-application")); _emberMetalCore["default"].assert("You cannot make a new Ember.Application using a root element that is a descendent of an existing Ember.Application", !rootElement.closest(".ember-application").length); _emberMetalCore["default"].assert("You cannot make a new Ember.Application using a root element that is an ancestor of an existing Ember.Application", !rootElement.find(".ember-application").length); rootElement.addClass("ember-application"); _emberMetalCore["default"].assert("Unable to add \"ember-application\" class to rootElement. Make sure you set rootElement to the body or an element in the body.", rootElement.is(".ember-application")); for (event in events) { if (events.hasOwnProperty(event)) { this.setupHandler(rootElement, event, events[event]); } } }, /** Registers an event listener on the rootElement. If the given event is triggered, the provided event handler will be triggered on the target view. If the target view does not implement the event handler, or if the handler returns `false`, the parent view will be called. The event will continue to bubble to each successive parent view until it reaches the top. @private @method setupHandler @param {Element} rootElement @param {String} event the browser-originated event to listen to @param {String} eventName the name of the method to call on the view */ setupHandler: function (rootElement, event, eventName) { var self = this; var viewRegistry = this.container && this.container.lookup("-view-registry:main") || _emberViewsViewsView["default"].views; rootElement.on(event + ".ember", ".ember-view", function (evt, triggeringManager) { var view = viewRegistry[this.id]; var result = true; var manager = self.canDispatchToEventManager ? self._findNearestEventManager(view, eventName) : null; if (manager && manager !== triggeringManager) { result = self._dispatchEvent(manager, evt, eventName, view); } else if (view) { result = self._bubbleEvent(view, evt, eventName); } return result; }); rootElement.on(event + ".ember", "[data-ember-action]", function (evt) { var actionId = _emberViewsSystemJquery["default"](evt.currentTarget).attr("data-ember-action"); var actions = _emberViewsSystemAction_manager["default"].registeredActions[actionId]; // We have to check for actions here since in some cases, jQuery will trigger // an event on `removeChild` (i.e. focusout) after we've already torn down the // action handlers for the view. if (!actions) { return; } for (var index = 0, _length = actions.length; index < _length; index++) { var action = actions[index]; if (action && action.eventName === eventName) { return action.handler(evt); } } }); }, _findNearestEventManager: function (view, eventName) { var manager = null; while (view) { manager = _emberMetalProperty_get.get(view, "eventManager"); if (manager && manager[eventName]) { break; } view = _emberMetalProperty_get.get(view, "parentView"); } return manager; }, _dispatchEvent: function (object, evt, eventName, view) { var result = true; var handler = object[eventName]; if (typeof handler === "function") { result = _emberMetalRun_loop["default"](object, handler, evt, view); // Do not preventDefault in eventManagers. evt.stopPropagation(); } else { result = this._bubbleEvent(view, evt, eventName); } return result; }, _bubbleEvent: function (view, evt, eventName) { return _emberMetalRun_loop["default"].join(view, view.handleEvent, eventName, evt); }, destroy: function () { var rootElement = _emberMetalProperty_get.get(this, "rootElement"); _emberViewsSystemJquery["default"](rootElement).off(".ember", "**").removeClass("ember-application"); return this._super.apply(this, arguments); }, toString: function () { return "(EventDispatcher)"; } }); }); /** @module ember @submodule ember-views */ // Ember.assert enifed('ember-views/system/ext', ['exports', 'ember-metal/run_loop'], function (exports, _emberMetalRun_loop) { // Add a new named queue for rendering views that happens // after bindings have synced, and a queue for scheduling actions // that that should occur after view rendering. _emberMetalRun_loop["default"]._addQueue('render', 'actions'); _emberMetalRun_loop["default"]._addQueue('afterRender', 'render'); }); /** @module ember @submodule ember-views */ enifed('ember-views/system/jquery', ['exports', 'ember-metal/core', 'ember-metal/enumerable_utils', 'ember-metal/environment'], function (exports, _emberMetalCore, _emberMetalEnumerable_utils, _emberMetalEnvironment) { var jQuery; if (_emberMetalEnvironment["default"].hasDOM) { // mainContext is set in `package/loader/lib/main.js` to the `this` context before entering strict mode jQuery = _emberMetalCore["default"].imports && _emberMetalCore["default"].imports.jQuery || mainContext && mainContext.jQuery; //jshint ignore:line if (!jQuery && typeof eriuqer === 'function') { jQuery = eriuqer('jquery'); } _emberMetalCore["default"].assert('Ember Views require jQuery between 1.7 and 2.1', jQuery && (jQuery().jquery.match(/^((1\.(7|8|9|10|11))|(2\.(0|1)))(\.\d+)?(pre|rc\d?)?/) || _emberMetalCore["default"].ENV.FORCE_JQUERY)); if (jQuery) { // http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#dndevents var dragEvents = ['dragstart', 'drag', 'dragenter', 'dragleave', 'dragover', 'drop', 'dragend']; // Copies the `dataTransfer` property from a browser event object onto the // jQuery event object for the specified events _emberMetalEnumerable_utils.forEach(dragEvents, function (eventName) { jQuery.event.fixHooks[eventName] = { props: ['dataTransfer'] }; }); } } exports["default"] = jQuery; }); // Ember.assert // ES6TODO: the functions on EnumerableUtils need their own exports enifed("ember-views/system/lookup_partial", ["exports", "ember-metal/core", "ember-metal/error"], function (exports, _emberMetalCore, _emberMetalError) { exports["default"] = lookupPartial; function lookupPartial(env, templateName) { if (templateName == null) { return; } var nameParts = templateName.split("/"); var lastPart = nameParts[nameParts.length - 1]; nameParts[nameParts.length - 1] = "_" + lastPart; var underscoredName = nameParts.join("/"); var template = templateFor(env, underscoredName, templateName); _emberMetalCore["default"].assert("Unable to find partial with name \"" + templateName + "\"", !!template); return template; } function templateFor(env, underscored, name) { if (!name) { return; } _emberMetalCore["default"].assert("templateNames are not allowed to contain periods: " + name, name.indexOf(".") === -1); if (!env.container) { throw new _emberMetalError["default"]("Container was not found when looking up a views template. " + "This is most likely due to manually instantiating an Ember.View. " + "See: http://git.io/EKPpnA"); } return env.container.lookup("template:" + underscored) || env.container.lookup("template:" + name); } }); // Ember.assert enifed('ember-views/system/platform', ['exports', 'ember-metal/environment'], function (exports, _emberMetalEnvironment) { // IE 6/7 have bugs around setting names on inputs during creation. // From http://msdn.microsoft.com/en-us/library/ie/ms536389(v=vs.85).aspx: // "To include the NAME attribute at run time on objects created with the createElement method, use the eTag." var canSetNameOnInputs = _emberMetalEnvironment["default"].hasDOM && (function () { var div = document.createElement('div'); var el = document.createElement('input'); el.setAttribute('name', 'foo'); div.appendChild(el); return !!div.innerHTML.match('foo'); })(); exports.canSetNameOnInputs = canSetNameOnInputs; }); enifed("ember-views/system/utils", ["exports"], function (exports) { exports.isSimpleClick = isSimpleClick; exports.getViewClientRects = getViewClientRects; exports.getViewBoundingClientRect = getViewBoundingClientRect; /** @module ember @submodule ember-views */ function isSimpleClick(event) { var modifier = event.shiftKey || event.metaKey || event.altKey || event.ctrlKey; var secondaryClick = event.which > 1; // IE9 may return undefined return !modifier && !secondaryClick; } /** @private @method getViewRange @param {Ember.View} view */ function getViewRange(view) { var range = document.createRange(); range.setStartBefore(view._renderNode.firstNode); range.setEndAfter(view._renderNode.lastNode); return range; } /** `getViewClientRects` provides information about the position of the border box edges of a view relative to the viewport. It is only intended to be used by development tools like the Ember Inspector and may not work on older browsers. @private @method getViewClientRects @param {Ember.View} view */ function getViewClientRects(view) { var range = getViewRange(view); return range.getClientRects(); } /** `getViewBoundingClientRect` provides information about the position of the bounding border box edges of a view relative to the viewport. It is only intended to be used by development tools like the Ember Inpsector and may not work on older browsers. @private @method getViewBoundingClientRect @param {Ember.View} view */ function getViewBoundingClientRect(view) { var range = getViewRange(view); return range.getBoundingClientRect(); } }); enifed("ember-views/views/checkbox", ["exports", "ember-metal/property_get", "ember-metal/property_set", "ember-views/views/view"], function (exports, _emberMetalProperty_get, _emberMetalProperty_set, _emberViewsViewsView) { /** @module ember @submodule ember-views */ /** The internal class used to create text inputs when the `{{input}}` helper is used with `type` of `checkbox`. See [Ember.Templates.helpers.input](/api/classes/Ember.Templates.helpers.html#method_input) for usage details. ## Direct manipulation of `checked` The `checked` attribute of an `Ember.Checkbox` object should always be set through the Ember object or by interacting with its rendered element representation via the mouse, keyboard, or touch. Updating the value of the checkbox via jQuery will result in the checked value of the object and its element losing synchronization. ## Layout and LayoutName properties Because HTML `input` elements are self closing `layout` and `layoutName` properties will not be applied. See [Ember.View](/api/classes/Ember.View.html)'s layout section for more information. @class Checkbox @namespace Ember @extends Ember.View @public */ // 2.0TODO: Subclass Component rather than View exports["default"] = _emberViewsViewsView["default"].extend({ instrumentDisplay: "{{input type=\"checkbox\"}}", classNames: ["ember-checkbox"], tagName: "input", attributeBindings: ["type", "checked", "indeterminate", "disabled", "tabindex", "name", "autofocus", "required", "form"], type: "checkbox", checked: false, disabled: false, indeterminate: false, init: function () { this._super.apply(this, arguments); this.on("change", this, this._updateElementValue); }, didInsertElement: function () { this._super.apply(this, arguments); _emberMetalProperty_get.get(this, "element").indeterminate = !!_emberMetalProperty_get.get(this, "indeterminate"); }, _updateElementValue: function () { _emberMetalProperty_set.set(this, "checked", this.$().prop("checked")); } }); }); enifed("ember-views/views/collection_view", ["exports", "ember-metal/core", "ember-views/views/container_view", "ember-views/views/view", "ember-runtime/mixins/array", "ember-metal/property_get", "ember-metal/property_set", "ember-runtime/system/string", "ember-metal/computed", "ember-metal/mixin", "ember-views/streams/utils", "ember-views/mixins/empty_view_support"], function (exports, _emberMetalCore, _emberViewsViewsContainer_view, _emberViewsViewsView, _emberRuntimeMixinsArray, _emberMetalProperty_get, _emberMetalProperty_set, _emberRuntimeSystemString, _emberMetalComputed, _emberMetalMixin, _emberViewsStreamsUtils, _emberViewsMixinsEmpty_view_support) { /** `Ember.CollectionView` is an `Ember.View` descendent responsible for managing a collection (an array or array-like object) by maintaining a child view object and associated DOM representation for each item in the array and ensuring that child views and their associated rendered HTML are updated when items in the array are added, removed, or replaced. ## Setting content The managed collection of objects is referenced as the `Ember.CollectionView` instance's `content` property. ```javascript someItemsView = Ember.CollectionView.create({ content: ['A', 'B','C'] }) ``` The view for each item in the collection will have its `content` property set to the item. ## Specifying `itemViewClass` By default the view class for each item in the managed collection will be an instance of `Ember.View`. You can supply a different class by setting the `CollectionView`'s `itemViewClass` property. Given the following application code: ```javascript var App = Ember.Application.create(); App.ItemListView = Ember.CollectionView.extend({ classNames: ['a-collection'], content: ['A','B','C'], itemViewClass: Ember.View.extend({ template: Ember.HTMLBars.compile("the letter: {{view.content}}") }) }); ``` And a simple application template: ```handlebars {{view 'item-list'}} ``` The following HTML will result: ```html
    the letter: A
    the letter: B
    the letter: C
    ``` ## Automatic matching of parent/child tagNames Setting the `tagName` property of a `CollectionView` to any of "ul", "ol", "table", "thead", "tbody", "tfoot", "tr", or "select" will result in the item views receiving an appropriately matched `tagName` property. Given the following application code: ```javascript var App = Ember.Application.create(); App.UnorderedListView = Ember.CollectionView.create({ tagName: 'ul', content: ['A','B','C'], itemViewClass: Ember.View.extend({ template: Ember.HTMLBars.compile("the letter: {{view.content}}") }) }); ``` And a simple application template: ```handlebars {{view 'unordered-list-view'}} ``` The following HTML will result: ```html ``` Additional `tagName` pairs can be provided by adding to `Ember.CollectionView.CONTAINER_MAP`. For example: ```javascript Ember.CollectionView.CONTAINER_MAP['article'] = 'section' ``` ## Programmatic creation of child views For cases where additional customization beyond the use of a single `itemViewClass` or `tagName` matching is required CollectionView's `createChildView` method can be overridden: ```javascript App.CustomCollectionView = Ember.CollectionView.extend({ createChildView: function(viewClass, attrs) { if (attrs.content.kind == 'album') { viewClass = App.AlbumView; } else { viewClass = App.SongView; } return this._super(viewClass, attrs); } }); ``` ## Empty View You can provide an `Ember.View` subclass to the `Ember.CollectionView` instance as its `emptyView` property. If the `content` property of a `CollectionView` is set to `null` or an empty array, an instance of this view will be the `CollectionView`s only child. ```javascript var App = Ember.Application.create(); App.ListWithNothing = Ember.CollectionView.create({ classNames: ['nothing'], content: null, emptyView: Ember.View.extend({ template: Ember.HTMLBars.compile("The collection is empty") }) }); ``` And a simple application template: ```handlebars {{view 'list-with-nothing'}} ``` The following HTML will result: ```html
    The collection is empty
    ``` ## Adding and Removing items The `childViews` property of a `CollectionView` should not be directly manipulated. Instead, add, remove, replace items from its `content` property. This will trigger appropriate changes to its rendered HTML. @class CollectionView @namespace Ember @extends Ember.ContainerView @uses Ember.EmptyViewSupport @since Ember 0.9 @private */ var CollectionView = _emberViewsViewsContainer_view["default"].extend(_emberViewsMixinsEmpty_view_support["default"], { /** A list of items to be displayed by the `Ember.CollectionView`. @property content @type Ember.Array @default null @private */ content: null, /** @property itemViewClass @type Ember.View @default Ember.View @private */ itemViewClass: _emberViewsViewsView["default"], /** Setup a CollectionView @method init @private */ init: function () { var ret = this._super.apply(this, arguments); this._contentDidChange(); return ret; }, /** Invoked when the content property is about to change. Notifies observers that the entire array content will change. @private @method _contentWillChange */ _contentWillChange: _emberMetalMixin._beforeObserver("content", function () { var content = this.get("content"); if (content) { content.removeArrayObserver(this); } var len = content ? _emberMetalProperty_get.get(content, "length") : 0; this.arrayWillChange(content, 0, len); }), /** Check to make sure that the content has changed, and if so, update the children directly. This is always scheduled asynchronously, to allow the element to be created before bindings have synchronized and vice versa. @private @method _contentDidChange */ _contentDidChange: _emberMetalMixin.observer("content", function () { var content = _emberMetalProperty_get.get(this, "content"); if (content) { this._assertArrayLike(content); content.addArrayObserver(this); } var len = content ? _emberMetalProperty_get.get(content, "length") : 0; this.arrayDidChange(content, 0, null, len); }), /** Ensure that the content implements Ember.Array @private @method _assertArrayLike */ _assertArrayLike: function (content) { _emberMetalCore["default"].assert(_emberRuntimeSystemString.fmt("an Ember.CollectionView's content must implement Ember.Array. You passed %@", [content]), _emberRuntimeMixinsArray["default"].detect(content)); }, /** Removes the content and content observers. @method destroy @private */ destroy: function () { if (!this._super.apply(this, arguments)) { return; } var content = _emberMetalProperty_get.get(this, "content"); if (content) { content.removeArrayObserver(this); } if (this._createdEmptyView) { this._createdEmptyView.destroy(); } return this; }, /** Called when a mutation to the underlying content array will occur. This method will remove any views that are no longer in the underlying content array. Invokes whenever the content array itself will change. @method arrayWillChange @param {Array} content the managed collection of objects @param {Number} start the index at which the changes will occur @param {Number} removed number of object to be removed from content @private */ arrayWillChange: function (content, start, removedCount) { this.replace(start, removedCount, []); }, /** Called when a mutation to the underlying content array occurs. This method will replay that mutation against the views that compose the `Ember.CollectionView`, ensuring that the view reflects the model. This array observer is added in `contentDidChange`. @method arrayDidChange @param {Array} content the managed collection of objects @param {Number} start the index at which the changes occurred @param {Number} removed number of object removed from content @param {Number} added number of object added to content @private */ arrayDidChange: function (content, start, removed, added) { var addedViews = []; var view, item, idx, len, itemViewClass, itemViewProps; len = content ? _emberMetalProperty_get.get(content, "length") : 0; if (len) { itemViewProps = this._itemViewProps || {}; itemViewClass = this.getAttr("itemViewClass") || _emberMetalProperty_get.get(this, "itemViewClass"); itemViewClass = _emberViewsStreamsUtils.readViewFactory(itemViewClass, this.container); for (idx = start; idx < start + added; idx++) { item = content.objectAt(idx); itemViewProps._context = this.keyword ? this.get("context") : item; itemViewProps.content = item; itemViewProps.contentIndex = idx; view = this.createChildView(itemViewClass, itemViewProps); addedViews.push(view); } this.replace(start, 0, addedViews); } }, /** Instantiates a view to be added to the childViews array during view initialization. You generally will not call this method directly unless you are overriding `createChildViews()`. Note that this method will automatically configure the correct settings on the new view instance to act as a child of the parent. The tag name for the view will be set to the tagName of the viewClass passed in. @method createChildView @param {Class} viewClass @param {Object} [attrs] Attributes to add @return {Ember.View} new instance @private */ createChildView: function (_view, attrs) { var view = this._super(_view, attrs); var itemTagName = _emberMetalProperty_get.get(view, "tagName"); if (itemTagName === null || itemTagName === undefined) { itemTagName = CollectionView.CONTAINER_MAP[_emberMetalProperty_get.get(this, "tagName")]; _emberMetalProperty_set.set(view, "tagName", itemTagName); } return view; }, _willRender: function () { var attrs = this.attrs; var itemProps = buildItemViewProps(this._itemViewTemplate, attrs); this._itemViewProps = itemProps; var childViews = _emberMetalProperty_get.get(this, "childViews"); for (var i = 0, l = childViews.length; i < l; i++) { childViews[i].setProperties(itemProps); } if ("content" in attrs) { _emberMetalProperty_set.set(this, "content", this.getAttr("content")); } if ("emptyView" in attrs) { _emberMetalProperty_set.set(this, "emptyView", this.getAttr("emptyView")); } }, _emptyViewTagName: _emberMetalComputed.computed("tagName", function () { var tagName = _emberMetalProperty_get.get(this, "tagName"); return CollectionView.CONTAINER_MAP[tagName] || "div"; }) }); /** A map of parent tags to their default child tags. You can add additional parent tags if you want collection views that use a particular parent tag to default to a child tag. @property CONTAINER_MAP @type Object @static @final @private */ CollectionView.CONTAINER_MAP = { ul: "li", ol: "li", table: "tr", thead: "tr", tbody: "tr", tfoot: "tr", tr: "td", select: "option" }; var CONTAINER_MAP = CollectionView.CONTAINER_MAP; exports.CONTAINER_MAP = CONTAINER_MAP; function buildItemViewProps(template, attrs) { var props = {}; // Go through options passed to the {{collection}} helper and extract options // that configure item views instead of the collection itself. for (var prop in attrs) { if (prop === "itemViewClass" || prop === "itemController" || prop === "itemClassBinding") { continue; } if (attrs.hasOwnProperty(prop)) { var match = prop.match(/^item(.)(.*)$/); if (match) { var childProp = match[1].toLowerCase() + match[2]; if (childProp === "class" || childProp === "classNames") { props.classNames = [attrs[prop]]; } else { props[childProp] = attrs[prop]; } delete attrs[prop]; } } } if (template) { props.template = template; } return props; } exports["default"] = CollectionView; }); /** @module ember @submodule ember-views */ // Ember.assert enifed("ember-views/views/component", ["exports", "ember-metal/core", "ember-views/mixins/component_template_deprecation", "ember-runtime/mixins/target_action_support", "ember-views/views/view", "ember-metal/property_get", "ember-metal/property_set", "ember-metal/is_none", "ember-metal/computed", "ember-views/compat/attrs-proxy"], function (exports, _emberMetalCore, _emberViewsMixinsComponent_template_deprecation, _emberRuntimeMixinsTarget_action_support, _emberViewsViewsView, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalIs_none, _emberMetalComputed, _emberViewsCompatAttrsProxy) { function validateAction(component, actionName) { if (actionName && actionName[_emberViewsCompatAttrsProxy.MUTABLE_CELL]) { actionName = actionName.value; } _emberMetalCore["default"].assert("The default action was triggered on the component " + component.toString() + ", but the action name (" + actionName + ") was not a string.", _emberMetalIs_none["default"](actionName) || typeof actionName === "string" || typeof actionName === "function"); return actionName; } /** @module ember @submodule ember-views */ /** An `Ember.Component` is a view that is completely isolated. Properties accessed in its templates go to the view object and actions are targeted at the view object. There is no access to the surrounding context or outer controller; all contextual information must be passed in. The easiest way to create an `Ember.Component` is via a template. If you name a template `components/my-foo`, you will be able to use `{{my-foo}}` in other templates, which will make an instance of the isolated component. ```handlebars {{app-profile person=currentUser}} ``` ```handlebars

    {{person.title}}

    {{person.signature}}

    ``` You can use `yield` inside a template to include the **contents** of any block attached to the component. The block will be executed in the context of the surrounding context or outer controller: ```handlebars {{#app-profile person=currentUser}}

    Admin mode

    {{! Executed in the controller's context. }} {{/app-profile}} ``` ```handlebars

    {{person.title}}

    {{! Executed in the components context. }} {{yield}} {{! block contents }} ``` If you want to customize the component, in order to handle events or actions, you implement a subclass of `Ember.Component` named after the name of the component. Note that `Component` needs to be appended to the name of your subclass like `AppProfileComponent`. For example, you could implement the action `hello` for the `app-profile` component: ```javascript App.AppProfileComponent = Ember.Component.extend({ actions: { hello: function(name) { console.log("Hello", name); } } }); ``` And then use it in the component's template: ```handlebars

    {{person.title}}

    {{yield}} ``` 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 @public */ var Component = _emberViewsViewsView["default"].extend(_emberRuntimeMixinsTarget_action_support["default"], _emberViewsMixinsComponent_template_deprecation["default"], { isComponent: true, /* 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: _emberMetalComputed.computed(function () { if (this._debugContainerKey) { return "{{" + this._debugContainerKey.split(":")[1] + "}}"; } }), init: function () { this._super.apply(this, arguments); _emberMetalProperty_set.set(this, "controller", this); _emberMetalProperty_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 @public */ template: _emberMetalComputed.computed("_template", { get: function () { _emberMetalCore["default"].deprecate("Accessing 'template' in " + this + " is deprecated. To determine if a block was specified to " + this + " please use '{{#if hasBlock}}' in the components layout."); return _emberMetalProperty_get.get(this, "_template"); }, set: function (key, value) { return _emberMetalProperty_set.set(this, "_template", value); } }), _template: _emberMetalComputed.computed("templateName", { get: function () { if (_emberMetalProperty_get.get(this, "_deprecatedFlagForBlockProvided")) { return true; } var templateName = _emberMetalProperty_get.get(this, "templateName"); var template = this.templateForName(templateName, "template"); _emberMetalCore["default"].assert("You specified the templateName " + templateName + " for " + this + ", but it did not exist.", !templateName || !!template); return template || _emberMetalProperty_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 @public */ 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 @private */ targetObject: _emberMetalComputed.computed("controller", function (key) { if (this._targetObject) { return this._targetObject; } if (this._controller) { return this._controller; } var parentView = _emberMetalProperty_get.get(this, "parentView"); return parentView ? _emberMetalProperty_get.get(parentView, "controller") : null; }), /** Calls a action passed to a component. 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/components/play-button.js export default Ember.Component.extend({ click() { if (this.get('isPlaying')) { this.sendAction('play'); } else { this.sendAction('stop'); } } }); ``` The actions "play" and "stop" must be passed to this `play-button` component: ```handlebars {{! app/templates/application.hbs }} {{play-button play=(action "musicStarted") stop=(action "musicStopped")}} ``` When the component receives a browser `click` event it translate this interaction into application-specific semantics ("play" or "stop") and calls the specified action. ```javascript // app/controller/application.js export default Ember.Controller.extend({ actions: { musicStarted() { // called when the play button is clicked // and the music started playing }, musicStopped() { // called when the play button is clicked // and the music stopped playing } } }); ``` If no action is passed to `sendAction` a default name of "action" is assumed. ```javascript // app/components/next-button.js export default Ember.Component.extend({ click() { this.sendAction(); } }); ``` ```handlebars {{! app/templates/application.hbs }} {{next-button action=(action "playNextSongInAlbum")}} ``` ```javascript // app/controllers/application.js App.ApplicationController = Ember.Controller.extend({ actions: { playNextSongInAlbum() { ... } } }); ``` @method sendAction @param [action] {String} the action to call @param [params] {*} arguments for the action @public */ sendAction: function (action) { var actionName; // Send the default action if (action === undefined) { action = "action"; } actionName = _emberMetalProperty_get.get(this, "attrs." + action) || _emberMetalProperty_get.get(this, action); actionName = validateAction(this, actionName); // If no action name for that action could be found, just abort. if (actionName === undefined) { return; } for (var _len = arguments.length, contexts = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { contexts[_key - 1] = arguments[_key]; } 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 = _emberMetalProperty_get.get(this, "target")) { _emberMetalCore["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(_emberMetalCore["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; }); // Ember.assert, Ember.Handlebars 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-metal/events", "ember-htmlbars/templates/container-view"], function (exports, _emberMetalCore, _emberRuntimeMixinsMutable_array, _emberViewsViewsView, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalEnumerable_utils, _emberMetalMixin, _emberMetalEvents, _emberHtmlbarsTemplatesContainerView) { _emberHtmlbarsTemplatesContainerView["default"].meta.revision = "Ember@1.13.4"; /** @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.HTMLBars.compile("A") }), bView: Ember.View.create({ template: Ember.HTMLBars.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.HTMLBars.compile("A") }), bView: Ember.View.create({ template: Ember.HTMLBars.compile("B") }) }); aContainer.appendTo('body'); ``` Results in the HTML ```html
    A
    B
    ``` Adding a view ```javascript AnotherViewClass = Ember.View.extend({ template: Ember.HTMLBars.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 @private */ var ContainerView = _emberViewsViewsView["default"].extend(_emberRuntimeMixinsMutable_array["default"], { willWatchProperty: function (prop) { _emberMetalCore["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 = _emberMetalProperty_get.get(this, "childViews"); _emberMetalCore["default"].deprecate("Setting `childViews` on a Container is deprecated.", _emberMetalCore["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 = _emberMetalCore["default"].A([]); _emberMetalEnumerable_utils.forEach(userChildViews, function (viewName, idx) { var view; if ("string" === typeof viewName) { view = _emberMetalProperty_get.get(this, viewName); view = this.createChildView(view); _emberMetalProperty_set.set(this, viewName, view); } else { view = this.createChildView(viewName); } childViews[idx] = view; }, this); var currentView = _emberMetalProperty_get.get(this, "currentView"); if (currentView) { if (!childViews.length) { childViews = this.childViews = _emberMetalCore["default"].A(this.childViews.slice()); } childViews.push(this.createChildView(currentView)); } _emberMetalProperty_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: _emberMetalMixin._beforeObserver("currentView", function () { var currentView = _emberMetalProperty_get.get(this, "currentView"); if (currentView) { currentView.destroy(); } }), _currentViewDidChange: _emberMetalMixin.observer("currentView", function () { var currentView = _emberMetalProperty_get.get(this, "currentView"); if (currentView) { _emberMetalCore["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: _emberHtmlbarsTemplatesContainerView["default"], replace: function (idx, removedCount) { var _this = this; var addedViews = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2]; var addedCount = _emberMetalProperty_get.get(addedViews, "length"); var childViews = _emberMetalProperty_get.get(this, "childViews"); _emberMetalCore["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); _emberMetalEnumerable_utils.forEach(removedViews, function (view) { return _this.unlinkChild(view); }); _emberMetalEnumerable_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; })); _emberMetalProperty_set.set(this, "length", childViews.length); return this; }, objectAt: function (idx) { return this.childViews[idx]; }, _triggerChildWillDestroyElement: _emberMetalEvents.on("willDestroyElement", function () { var childViews = this.childViews; if (childViews) { for (var i = 0; i < childViews.length; i++) { this.renderer.willDestroyElement(childViews[i]); } } }), _triggerChildDidDestroyElement: _emberMetalEvents.on("didDestroyElement", function () { var childViews = this.childViews; if (childViews) { for (var i = 0; i < childViews.length; i++) { this.renderer.didDestroyElement(childViews[i]); } } }) }); 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, _emberMetalViewsRenderer, _emberViewsViewsStates, _emberRuntimeSystemObject, _emberRuntimeMixinsEvented, _emberRuntimeMixinsAction_handler, _emberMetalProperty_get, _emberRuntimeUtils, _htmlbarsRuntime) { 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 @private */ var CoreView = _emberRuntimeSystemObject["default"].extend(_emberRuntimeMixinsEvented["default"], _emberRuntimeMixinsAction_handler["default"], { isView: true, _states: _emberViewsViewsStates.cloneStates(_emberViewsViewsStates.states), init: function () { this._super.apply(this, arguments); this._state = "preRender"; this.currentState = this._states.preRender; this._isVisible = _emberMetalProperty_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 _emberMetalViewsRenderer["default"](new DOMHelper()); this.renderer = renderer; } this._destroyingSubtreeForView = null; 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 @private */ 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 _emberRuntimeUtils.typeOf(this[name]) === "function" || this._super(name); }, destroy: function () { if (!this._super.apply(this, arguments)) { return; } this.currentState.cleanup(this); // If the destroyingSubtreeForView property is not set but we have an // associated render node, it means this view is being destroyed from user // code and not via a change in the templating layer (like an {{if}} // becoming falsy, for example). In this case, it is our responsibility to // make sure that any render nodes created as part of the rendering process // are cleaned up. if (!this.ownerView._destroyingSubtreeForView && this._renderNode) { Ember.assert("BUG: Render node exists without concomitant env.", this.ownerView.env); _htmlbarsRuntime.internal.clearMorph(this._renderNode, this.ownerView.env, true); } 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); } }); exports.DeprecatedCoreView = DeprecatedCoreView; var _domHelper; function domHelper() { return _domHelper = _domHelper || Ember.__loader.require("ember-htmlbars/system/dom-helper")["default"]; } exports["default"] = CoreView; }); 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, _emberHtmlbarsTemplatesLegacyEach, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalComputed, _emberViewsViewsView, _emberViewsViewsCollection_view, _emberViewsMixinsEmpty_view_support) { exports["default"] = _emberViewsViewsView["default"].extend(_emberViewsMixinsEmpty_view_support["default"], { template: _emberHtmlbarsTemplatesLegacyEach["default"], tagName: "", _arrayController: _emberMetalComputed.computed(function () { var itemController = this.getAttr("itemController"); var controller = _emberMetalProperty_get.get(this, "container").lookupFactory("controller:array").create({ _isVirtual: true, parentController: _emberMetalProperty_get.get(this, "controller"), itemController: itemController, target: _emberMetalProperty_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 = _emberMetalProperty_get.get(this, "_arrayController"); _emberMetalProperty_set.set(arrayController, "content", this.getAttrFor(attrs, "content")); } }, _arrangedContent: _emberMetalComputed.computed("attrs.content", function () { if (this.getAttr("itemController")) { return _emberMetalProperty_get.get(this, "_arrayController"); } return this.getAttr("content"); }), _itemTagName: _emberMetalComputed.computed(function () { var tagName = _emberMetalProperty_get.get(this, "tagName"); return _emberViewsViewsCollection_view.CONTAINER_MAP[tagName]; }) }); }); //2.0TODO: Remove this in 2.0 //This is a fallback path for the `{{#each}}` helper that supports deprecated //behavior such as itemController. 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, _emberMetalEnumerable_utils, _emberMetalProperty_get, _emberMetalProperty_set, _emberViewsViewsView, _emberRuntimeUtils, _emberMetalIs_none, _emberMetalComputed, _emberRuntimeSystemNative_array, _emberMetalMixin, _emberMetalProperties, _emberHtmlbarsTemplatesSelect, _emberHtmlbarsTemplatesSelectOption, _emberHtmlbarsTemplatesSelectOptgroup) { var defaultTemplate = _emberHtmlbarsTemplatesSelect["default"]; var SelectOption = _emberViewsViewsView["default"].extend({ instrumentDisplay: "Ember.SelectOption", tagName: "option", attributeBindings: ["value", "selected"], defaultTemplate: _emberHtmlbarsTemplatesSelectOption["default"], content: null, _willRender: function () { this.labelPathDidChange(); this.valuePathDidChange(); }, selected: _emberMetalComputed.computed(function () { var value = _emberMetalProperty_get.get(this, "value"); var selection = _emberMetalProperty_get.get(this, "attrs.selection"); if (_emberMetalProperty_get.get(this, "attrs.multiple")) { return selection && _emberMetalEnumerable_utils.indexOf(selection, value) > -1; } else { // Primitives get passed through bindings as objects... since // `new Number(4) !== 4`, we use `==` below return value == _emberMetalProperty_get.get(this, "attrs.parentValue"); // jshint ignore:line } }).property("attrs.content", "attrs.selection"), labelPathDidChange: _emberMetalMixin.observer("attrs.optionLabelPath", function () { var labelPath = _emberMetalProperty_get.get(this, "attrs.optionLabelPath"); _emberMetalProperties.defineProperty(this, "label", _emberMetalComputed.computed.alias(labelPath)); }), valuePathDidChange: _emberMetalMixin.observer("attrs.optionValuePath", function () { var valuePath = _emberMetalProperty_get.get(this, "attrs.optionValuePath"); _emberMetalProperties.defineProperty(this, "value", _emberMetalComputed.computed.alias(valuePath)); }) }); var SelectOptgroup = _emberViewsViewsView["default"].extend({ instrumentDisplay: "Ember.SelectOptgroup", tagName: "optgroup", defaultTemplate: _emberHtmlbarsTemplatesSelectOptgroup["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 `