Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
diff -u gem.js web.js
This file has been truncated, but you can view the full file.
--- gem.js 2015-04-24 11:35:45.000000000 +0900
+++ web.js 2015-04-24 11:36:43.000000000 +0900
@@ -1107,7 +1107,7 @@
*/
Ember.MODEL_FACTORY_INJECTIONS = false;
- if (Ember.ENV && typeof Ember.ENV.MODEL_FACTORY_INJECTIONS !== "undefined") {
+ if (Ember.ENV && typeof Ember.ENV.MODEL_FACTORY_INJECTIONS !== 'undefined') {
Ember.MODEL_FACTORY_INJECTIONS = !!Ember.ENV.MODEL_FACTORY_INJECTIONS;
}
@@ -1135,18 +1135,20 @@
@class Container
*/
function Container(registry, options) {
- this._registry = registry || (function () {
- Ember['default'].deprecate("A container should only be created for an already instantiated " + "registry. For backward compatibility, an isolated registry will " + "be instantiated just for this container.");
+ this._registry = registry || (function() {
+ Ember['default'].deprecate(
+ "A container should only be created for an already instantiated " +
+ "registry. For backward compatibility, an isolated registry will " +
+ "be instantiated just for this container."
+ );
// TODO - See note above about transpiler import workaround.
- if (!Registry) {
- Registry = requireModule("container/registry")["default"];
- }
+ if (!Registry) { Registry = requireModule('container/registry')['default']; }
return new Registry();
- })();
+ }());
- this.cache = dictionary['default'](options && options.cache ? options.cache : null);
+ this.cache = dictionary['default'](options && options.cache ? options.cache : null);
this.factoryCache = dictionary['default'](options && options.factoryCache ? options.factoryCache : null);
this.validationCache = dictionary['default'](options && options.validationCache ? options.validationCache : null);
}
@@ -1154,7 +1156,8 @@
Container.prototype = {
/**
@private
- @property _registry
+
+ @property _registry
@type Registry
@since 1.11.0
*/
@@ -1180,57 +1183,72 @@
/**
Given a fullName return a corresponding instance.
- The default behaviour is for lookup to return a singleton 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
+
+ ```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
+
+ 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
+
+ twitter === twitter2; //=> true
```
- If singletons are not wanted an optional flag can be provided at lookup.
- ```javascript
+
+ 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 });
+
+ registry.register('api:twitter', Twitter);
+
+ var twitter = container.lookup('api:twitter', { singleton: false });
var twitter2 = container.lookup('api:twitter', { singleton: false });
- twitter === twitter2; //=> false
+
+ twitter === twitter2; //=> false
```
- @method lookup
+
+ @method lookup
@param {String} fullName
@param {Object} options
@return {any}
*/
- lookup: function (fullName, options) {
- Ember['default'].assert("fullName must be a proper full name", this._registry.validateFullName(fullName));
+ lookup: function(fullName, options) {
+ Ember['default'].assert('fullName must be a proper full name', this._registry.validateFullName(fullName));
return lookup(this, this._registry.normalize(fullName), options);
},
/**
Given a fullName return the corresponding factory.
- @method lookupFactory
+
+ @method lookupFactory
@param {String} fullName
@return {any}
*/
- lookupFactory: function (fullName) {
- Ember['default'].assert("fullName must be a proper full name", this._registry.validateFullName(fullName));
+ lookupFactory: function(fullName) {
+ Ember['default'].assert('fullName must be a proper full name', this._registry.validateFullName(fullName));
return factoryFor(this, this._registry.normalize(fullName));
},
/**
A depth first traversal, destroying the container, its descendant containers and all
their managed objects.
- @method destroy
+
+ @method destroy
*/
- destroy: function () {
- eachDestroyable(this, function (item) {
+ destroy: function() {
+ eachDestroyable(this, function(item) {
if (item.destroy) {
item.destroy();
}
@@ -1241,10 +1259,11 @@
/**
Clear either the entire cache or just the cache for a particular key.
- @method reset
+
+ @method reset
@param {String} fullName optional key to reset; if missing, resets everything
*/
- reset: function (fullName) {
+ reset: function(fullName) {
if (arguments.length > 0) {
resetMember(this, this._registry.normalize(fullName));
} else {
@@ -1254,11 +1273,23 @@
};
(function exposeRegistryMethods() {
- var methods = ["register", "unregister", "resolve", "normalize", "typeInjection", "injection", "factoryInjection", "factoryTypeInjection", "has", "options", "optionsForType"];
+ var methods = [
+ 'register',
+ 'unregister',
+ 'resolve',
+ 'normalize',
+ 'typeInjection',
+ 'injection',
+ 'factoryInjection',
+ 'factoryTypeInjection',
+ 'has',
+ 'options',
+ 'optionsForType'
+ ];
function exposeRegistryMethod(method) {
- Container.prototype[method] = function () {
- Ember['default'].deprecate(method + " should be called on the registry instead of the container");
+ Container.prototype[method] = function() {
+ Ember['default'].deprecate(method + ' should be called on the registry instead of the container');
return this._registry[method].apply(this._registry, arguments);
};
}
@@ -1277,11 +1308,9 @@
var value = instantiate(container, fullName);
- if (value === undefined) {
- return;
- }
+ if (value === undefined) { return; }
- if (container._registry.getOption(fullName, "singleton") !== false && options.singleton !== false) {
+ if (container._registry.getOption(fullName, 'singleton') !== false && options.singleton !== false) {
container.cache[fullName] = value;
}
@@ -1320,13 +1349,11 @@
}
var registry = container._registry;
var factory = registry.resolve(fullName);
- if (factory === undefined) {
- return;
- }
+ if (factory === undefined) { return; }
- var type = fullName.split(":")[0];
- if (!factory || typeof factory.extend !== "function" || !Ember['default'].MODEL_FACTORY_INJECTIONS && type === "model") {
- if (factory && typeof factory._onLookup === "function") {
+ var type = fullName.split(':')[0];
+ if (!factory || typeof factory.extend !== 'function' || (!Ember['default'].MODEL_FACTORY_INJECTIONS && type === 'model')) {
+ if (factory && typeof factory._onLookup === 'function') {
factory._onLookup(fullName);
}
@@ -1334,6 +1361,7 @@
// for now just fallback to create time injection
cache[fullName] = factory;
return factory;
+
} else {
var injections = injectionsFor(container, fullName);
var factoryInjections = factoryInjectionsFor(container, fullName);
@@ -1343,7 +1371,7 @@
var injectedFactory = factory.extend(injections);
injectedFactory.reopenClass(factoryInjections);
- if (factory && typeof factory._onLookup === "function") {
+ if (factory && typeof factory._onLookup === 'function') {
factory._onLookup(fullName);
}
@@ -1355,10 +1383,12 @@
function injectionsFor(container, fullName) {
var registry = container._registry;
- var splitName = fullName.split(":");
+ var splitName = fullName.split(':');
var type = splitName[0];
- var injections = buildInjections(container, registry.getTypeInjections(type), registry.getInjections(fullName));
+ var injections = buildInjections(container,
+ registry.getTypeInjections(type),
+ registry.getInjections(fullName));
injections._debugContainerKey = fullName;
injections.container = container;
@@ -1367,10 +1397,12 @@
function factoryInjectionsFor(container, fullName) {
var registry = container._registry;
- var splitName = fullName.split(":");
+ var splitName = fullName.split(':');
var type = splitName[0];
- var factoryInjections = buildInjections(container, registry.getFactoryTypeInjections(type), registry.getFactoryInjections(fullName));
+ var factoryInjections = buildInjections(container,
+ registry.getFactoryTypeInjections(type),
+ registry.getFactoryInjections(fullName));
factoryInjections._debugContainerKey = fullName;
return factoryInjections;
@@ -1380,19 +1412,20 @@
var factory = factoryFor(container, fullName);
var lazyInjections, validationCache;
- if (container._registry.getOption(fullName, "instantiate") === false) {
+ 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.");
+ 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") {
+ if (!validationCache[fullName] && typeof factory._lazyInjections === 'function') {
lazyInjections = factory._lazyInjections();
lazyInjections = container._registry.normalizeInjectionsHash(lazyInjections);
@@ -1401,7 +1434,7 @@
validationCache[fullName] = true;
- if (typeof factory.extend === "function") {
+ if (typeof factory.extend === 'function') {
// assume the factory was extendable and is already injected
return factory.create();
} else {
@@ -1422,14 +1455,14 @@
key = keys[i];
value = cache[key];
- if (container._registry.getOption(key, "instantiate") !== false) {
+ if (container._registry.getOption(key, 'instantiate') !== false) {
callback(value);
}
}
}
function resetCache(container) {
- eachDestroyable(container, function (value) {
+ eachDestroyable(container, function(value) {
if (value.destroy) {
value.destroy();
}
@@ -1480,26 +1513,27 @@
function Registry(options) {
this.fallback = options && options.fallback ? options.fallback : null;
- this.resolver = options && options.resolver ? options.resolver : function () {};
+ this.resolver = options && options.resolver ? options.resolver : function() {};
- this.registrations = dictionary['default'](options && options.registrations ? options.registrations : null);
+ this.registrations = dictionary['default'](options && options.registrations ? options.registrations : null);
- this._typeInjections = dictionary['default'](null);
- this._injections = dictionary['default'](null);
+ this._typeInjections = dictionary['default'](null);
+ this._injections = dictionary['default'](null);
this._factoryTypeInjections = dictionary['default'](null);
- this._factoryInjections = dictionary['default'](null);
+ this._factoryInjections = dictionary['default'](null);
- this._normalizeCache = dictionary['default'](null);
- this._resolveCache = dictionary['default'](null);
+ this._normalizeCache = dictionary['default'](null);
+ this._resolveCache = dictionary['default'](null);
- this._options = dictionary['default'](null);
- this._typeOptions = dictionary['default'](null);
+ this._options = dictionary['default'](null);
+ this._typeOptions = dictionary['default'](null);
}
Registry.prototype = {
/**
A backup registry for resolving registrations when no matches can be found.
- @property fallback
+
+ @property fallback
@type Registry
*/
fallback: null,
@@ -1518,65 +1552,75 @@
/**
@private
- @property _typeInjections
+
+ @property _typeInjections
@type InheritingDict
*/
_typeInjections: null,
/**
@private
- @property _injections
+
+ @property _injections
@type InheritingDict
*/
_injections: null,
/**
@private
- @property _factoryTypeInjections
+
+ @property _factoryTypeInjections
@type InheritingDict
*/
_factoryTypeInjections: null,
/**
@private
- @property _factoryInjections
+
+ @property _factoryInjections
@type InheritingDict
*/
_factoryInjections: null,
/**
@private
- @property _normalizeCache
+
+ @property _normalizeCache
@type InheritingDict
*/
_normalizeCache: null,
/**
@private
- @property _resolveCache
+
+ @property _resolveCache
@type InheritingDict
*/
_resolveCache: null,
/**
@private
- @property _options
+
+ @property _options
@type InheritingDict
*/
_options: null,
/**
@private
- @property _typeOptions
+
+ @property _typeOptions
@type InheritingDict
*/
_typeOptions: null,
/**
The first container created for this registry.
- This allows deprecated access to `lookup` and `lookupFactory` to avoid
+
+ This allows deprecated access to `lookup` and `lookupFactory` to avoid
breaking compatibility for Ember 1.x initializers.
- @private
+
+ @private
@property _defaultContainer
@type Container
*/
@@ -1584,11 +1628,12 @@
/**
Creates a container based on this registry.
- @method container
+
+ @method container
@param {Object} options
@return {Container} created container
*/
- container: function (options) {
+ container: function(options) {
var container = new Container['default'](this, options);
// 2.0TODO - remove `registerContainer`
@@ -1601,11 +1646,13 @@
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
+
+ 2.0TODO: Remove this method. The bookkeeping is only needed to support
deprecated behavior.
- @param {Container} newly created container
+
+ @param {Container} newly created container
*/
- registerContainer: function (container) {
+ registerContainer: function(container) {
if (!this._defaultContainer) {
this._defaultContainer = container;
}
@@ -1614,21 +1661,29 @@
}
},
- lookup: function (fullName, options) {
- Ember['default'].assert("Create a container on the registry (with `registry.container()`) before calling `lookup`.", this._defaultContainer);
+ lookup: function(fullName, options) {
+ Ember['default'].assert('Create a container on the registry (with `registry.container()`) before calling `lookup`.', this._defaultContainer);
if (instanceInitializersFeatureEnabled) {
- Ember['default'].deprecate("`lookup` was called on a Registry. The `initializer` API no longer receives a container, and you should use an `instanceInitializer` to look up objects from the container.", false, { url: "http://emberjs.com/guides/deprecations#toc_access-to-instances-in-initializers" });
+ Ember['default'].deprecate(
+ '`lookup` was called on a Registry. The `initializer` API no longer receives a container, and you should use an `instanceInitializer` to look up objects from the container.',
+ false,
+ { url: "http://emberjs.com/guides/deprecations#toc_access-to-instances-in-initializers" }
+ );
}
return this._defaultContainer.lookup(fullName, options);
},
- lookupFactory: function (fullName) {
- Ember['default'].assert("Create a container on the registry (with `registry.container()`) before calling `lookupFactory`.", this._defaultContainer);
+ lookupFactory: function(fullName) {
+ Ember['default'].assert('Create a container on the registry (with `registry.container()`) before calling `lookupFactory`.', this._defaultContainer);
if (instanceInitializersFeatureEnabled) {
- Ember['default'].deprecate("`lookupFactory` was called on a Registry. The `initializer` API no longer receives a container, and you should use an `instanceInitializer` to look up objects from the container.", false, { url: "http://emberjs.com/guides/deprecations#toc_access-to-instances-in-initializers" });
+ Ember['default'].deprecate(
+ '`lookupFactory` was called on a Registry. The `initializer` API no longer receives a container, and you should use an `instanceInitializer` to look up objects from the container.',
+ false,
+ { url: "http://emberjs.com/guides/deprecations#toc_access-to-instances-in-initializers" }
+ );
}
return this._defaultContainer.lookupFactory(fullName);
@@ -1636,49 +1691,57 @@
/**
Registers a factory for later injection.
- Example:
- ```javascript
+
+ Example:
+
+ ```javascript
var registry = new Registry();
- registry.register('model:user', Person, {singleton: false });
+
+ registry.register('model:user', Person, {singleton: false });
registry.register('fruit:favorite', Orange);
registry.register('communication:main', Email, {singleton: false});
```
- @method register
+
+ @method register
@param {String} fullName
@param {Function} factory
@param {Object} options
*/
- register: function (fullName, factory, options) {
- Ember['default'].assert("fullName must be a proper full name", this.validateFullName(fullName));
+ register: function(fullName, factory, options) {
+ Ember['default'].assert('fullName must be a proper full name', this.validateFullName(fullName));
if (factory === undefined) {
- throw new TypeError("Attempting to register an unknown factory: `" + fullName + "`");
+ 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.");
+ throw new Error('Cannot re-register: `' + fullName +'`, as it has already been resolved.');
}
this.registrations[normalizedName] = factory;
- this._options[normalizedName] = options || {};
+ this._options[normalizedName] = (options || {});
},
/**
Unregister a fullName
- ```javascript
+
+ ```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').create() instanceof User //=> true
+
+ registry.unregister('model:user')
registry.resolve('model:user') === undefined //=> true
```
- @method unregister
+
+ @method unregister
@param {String} fullName
*/
- unregister: function (fullName) {
- Ember['default'].assert("fullName must be a proper full name", this.validateFullName(fullName));
+ unregister: function(fullName) {
+ Ember['default'].assert('fullName must be a proper full name', this.validateFullName(fullName));
var normalizedName = this.normalize(fullName);
@@ -1689,31 +1752,38 @@
/**
Given a fullName return the corresponding factory.
- By default `resolve` will retrieve the factory from
+
+ By default `resolve` will retrieve the factory from
the registry.
- ```javascript
+
+ ```javascript
var registry = new Registry();
registry.register('api:twitter', Twitter);
- registry.resolve('api:twitter') // => Twitter
+
+ registry.resolve('api:twitter') // => Twitter
```
- Optionally the registry can be provided with a custom resolver.
+
+ 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
+
+ ```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
+
+ // the twitter factory is added to the module system
registry.resolve('api:twitter') // => Twitter
```
- @method resolve
+
+ @method resolve
@param {String} fullName
@return {Function} fullName's factory
*/
- resolve: function (fullName) {
- Ember['default'].assert("fullName must be a proper full name", this.validateFullName(fullName));
+ resolve: function(fullName) {
+ Ember['default'].assert('fullName must be a proper full name', this.validateFullName(fullName));
var factory = resolve(this, this.normalize(fullName));
if (factory === undefined && this.fallback) {
factory = this.fallback.resolve(fullName);
@@ -1724,84 +1794,100 @@
/**
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
+
+ For example, the default Ember `.describe` returns the full
class name (including namespace) where Ember's resolver expects
to find the `fullName`.
- @method describe
+
+ @method describe
@param {String} fullName
@return {string} described fullName
*/
- describe: function (fullName) {
+ describe: function(fullName) {
return fullName;
},
/**
A hook to enable custom fullName normalization behaviour
- @method normalizeFullName
+
+ @method normalizeFullName
@param {String} fullName
@return {string} normalized fullName
*/
- normalizeFullName: function (fullName) {
+ normalizeFullName: function(fullName) {
return fullName;
},
/**
normalize a fullName based on the applications conventions
- @method normalize
+
+ @method normalize
@param {String} fullName
@return {string} normalized fullName
*/
- normalize: function (fullName) {
- return this._normalizeCache[fullName] || (this._normalizeCache[fullName] = this.normalizeFullName(fullName));
+ normalize: function(fullName) {
+ return this._normalizeCache[fullName] || (
+ this._normalizeCache[fullName] = this.normalizeFullName(fullName)
+ );
},
/**
@method makeToString
- @param {any} factory
+
+ @param {any} factory
@param {string} fullName
@return {function} toString function
*/
- makeToString: function (factory, fullName) {
+ makeToString: function(factory, fullName) {
return factory.toString();
},
/**
Given a fullName check if the container is aware of its factory
or singleton instance.
- @method has
+
+ @method has
@param {String} fullName
@return {Boolean}
*/
- has: function (fullName) {
- Ember['default'].assert("fullName must be a proper full name", this.validateFullName(fullName));
+ has: function(fullName) {
+ Ember['default'].assert('fullName must be a proper full name', this.validateFullName(fullName));
return has(this, this.normalize(fullName));
},
/**
Allow registering options for all factories of a type.
- ```javascript
+
+ ```javascript
var registry = new Registry();
var container = registry.container();
- // if all of type `connection` must not be singletons
+
+ // if all of type `connection` must not be singletons
registry.optionsForType('connection', { singleton: false });
- registry.register('connection:twitter', TwitterConnection);
+
+ registry.register('connection:twitter', TwitterConnection);
registry.register('connection:facebook', FacebookConnection);
- var twitter = container.lookup('connection:twitter');
+
+ var twitter = container.lookup('connection:twitter');
var twitter2 = container.lookup('connection:twitter');
- twitter === twitter2; // => false
- var facebook = container.lookup('connection:facebook');
+
+ twitter === twitter2; // => false
+
+ var facebook = container.lookup('connection:facebook');
var facebook2 = container.lookup('connection:facebook');
- facebook === facebook2; // => false
+
+ facebook === facebook2; // => false
```
- @method optionsForType
+
+ @method optionsForType
@param {String} type
@param {Object} options
*/
- optionsForType: function (type, options) {
+ optionsForType: function(type, options) {
this._typeOptions[type] = options;
},
- getOptionsForType: function (type) {
+ getOptionsForType: function(type) {
var optionsForType = this._typeOptions[type];
if (optionsForType === undefined && this.fallback) {
optionsForType = this.fallback.getOptionsForType(type);
@@ -1814,13 +1900,13 @@
@param {String} fullName
@param {Object} options
*/
- options: function (fullName, options) {
+ options: function(fullName, options) {
options = options || {};
var normalizedName = this.normalize(fullName);
this._options[normalizedName] = options;
},
- getOptions: function (fullName) {
+ getOptions: function(fullName) {
var normalizedName = this.normalize(fullName);
var options = this._options[normalizedName];
if (options === undefined && this.fallback) {
@@ -1829,64 +1915,76 @@
return options;
},
- getOption: function (fullName, optionName) {
+ getOption: function(fullName, optionName) {
var options = this._options[fullName];
if (options && options[optionName] !== undefined) {
return options[optionName];
}
- var type = fullName.split(":")[0];
+ var type = fullName.split(':')[0];
options = this._typeOptions[type];
if (options && options[optionName] !== undefined) {
return options[optionName];
+
} else if (this.fallback) {
return this.fallback.getOption(fullName, optionName);
}
},
- option: function (fullName, optionName) {
- Ember['default'].deprecate("`Registry.option()` has been deprecated. Call `Registry.getOption()` instead.");
+ option: function(fullName, optionName) {
+ Ember['default'].deprecate('`Registry.option()` has been deprecated. Call `Registry.getOption()` instead.');
return this.getOption(fullName, optionName);
},
/**
Used only via `injection`.
- Provides a specialized form of injection, specifically enabling
+
+ 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`.
+
+ For example, provided each object of type `controller` needed a `router`.
one would do the following:
- ```javascript
+
+ ```javascript
var registry = new Registry();
var container = registry.container();
- registry.register('router:main', Router);
+
+ 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');
+
+ registry.typeInjection('controller', 'router', 'router:main');
+
+ var user = container.lookup('controller:user');
var post = container.lookup('controller:post');
- user.router instanceof Router; //=> true
+
+ user.router instanceof Router; //=> true
post.router instanceof Router; //=> true
- // both controllers share the same router
+
+ // both controllers share the same router
user.router === post.router; //=> true
```
- @private
+
+ @private
@method typeInjection
@param {String} type
@param {String} property
@param {String} fullName
*/
- typeInjection: function (type, property, fullName) {
- Ember['default'].assert("fullName must be a proper full name", this.validateFullName(fullName));
+ typeInjection: function(type, property, fullName) {
+ Ember['default'].assert('fullName must be a proper full name', this.validateFullName(fullName));
- var fullNameType = fullName.split(":")[0];
+ var fullNameType = fullName.split(':')[0];
if (fullNameType === type) {
- throw new Error("Cannot inject a `" + fullName + "` on other " + type + "(s).");
+ throw new Error('Cannot inject a `' + fullName +
+ '` on other ' + type + '(s).');
}
- var injections = this._typeInjections[type] || (this._typeInjections[type] = []);
+ var injections = this._typeInjections[type] ||
+ (this._typeInjections[type] = []);
injections.push({
property: property,
@@ -1896,48 +1994,62 @@
/**
Defines injection rules.
- These rules are used to inject dependencies onto objects when they
+
+ 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
+
+ Two forms of injections are possible:
+
+ * Injecting one fullName on another fullName
* Injecting one fullName on a type
- Example:
- ```javascript
+
+ Example:
+
+ ```javascript
var registry = new Registry();
var container = registry.container();
- registry.register('source:main', Source);
+
+ registry.register('source:main', Source);
registry.register('model:user', User);
registry.register('model:post', Post);
- // injecting one fullName on another fullName
+
+ // 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
+
+ // injecting one fullName on another type
registry.injection('model', 'source', 'source:main');
- var user = container.lookup('model:user');
+
+ var user = container.lookup('model:user');
var post = container.lookup('model:post');
- user.source instanceof Source; //=> true
+
+ user.source instanceof Source; //=> true
post.source instanceof Source; //=> true
- user.post instanceof Post; //=> true
- // and both models share the same source
+
+ user.post instanceof Post; //=> true
+
+ // and both models share the same source
user.source === post.source; //=> true
```
- @method injection
+
+ @method injection
@param {String} factoryName
@param {String} property
@param {String} injectionName
*/
- injection: function (fullName, property, injectionName) {
+ injection: function(fullName, property, injectionName) {
this.validateFullName(injectionName);
var normalizedInjectionName = this.normalize(injectionName);
- if (fullName.indexOf(":") === -1) {
+ if (fullName.indexOf(':') === -1) {
return this.typeInjection(fullName, property, normalizedInjectionName);
}
- Ember['default'].assert("fullName must be a proper full name", this.validateFullName(fullName));
+ Ember['default'].assert('fullName must be a proper full name', this.validateFullName(fullName));
var normalizedName = this.normalize(fullName);
- var injections = this._injections[normalizedName] || (this._injections[normalizedName] = []);
+ var injections = this._injections[normalizedName] ||
+ (this._injections[normalizedName] = []);
injections.push({
property: property,
@@ -1945,29 +2057,39 @@
});
},
+
/**
Used only via `factoryInjection`.
- Provides a specialized form of injection, specifically enabling
+
+ 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`.
+
+ For example, provided each factory of type `model` needed a `store`.
one would do the following:
- ```javascript
+
+ ```javascript
var registry = new Registry();
- registry.register('store:main', SomeStore);
- registry.factoryTypeInjection('model', 'store', 'store:main');
- var store = registry.lookup('store:main');
+
+ 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
+
+ UserFactory.store instanceof SomeStore; //=> true
```
- @private
+
+ @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] = []);
+ factoryTypeInjection: function(type, property, fullName) {
+ var injections = this._factoryTypeInjections[type] ||
+ (this._factoryTypeInjections[type] = []);
injections.push({
property: property,
@@ -1977,47 +2099,61 @@
/**
Defines factory injection rules.
- Similar to regular injection rules, but are run against factories, via
+
+ Similar to regular injection rules, but are run against factories, via
`Registry#lookupFactory`.
- These rules are used to inject objects onto factories when they
+
+ 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
+
+ Two forms of injections are possible:
+
+ * Injecting one fullName on another fullName
* Injecting one fullName on a type
- Example:
- ```javascript
+
+ Example:
+
+ ```javascript
var registry = new Registry();
var container = registry.container();
- registry.register('store:main', Store);
+
+ 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
+
+ // injecting one fullName on another type
registry.factoryInjection('model', 'store', 'store:main');
- // injecting one fullName on another fullName
+
+ // injecting one fullName on another fullName
registry.factoryInjection('model:post', 'secondaryStore', 'store:secondary');
- var UserFactory = container.lookupFactory('model:user');
+
+ var UserFactory = container.lookupFactory('model:user');
var PostFactory = container.lookupFactory('model:post');
var store = container.lookup('store:main');
- UserFactory.store instanceof Store; //=> true
+
+ UserFactory.store instanceof Store; //=> true
UserFactory.secondaryStore instanceof OtherStore; //=> false
- PostFactory.store instanceof Store; //=> true
+
+ PostFactory.store instanceof Store; //=> true
PostFactory.secondaryStore instanceof OtherStore; //=> true
- // and both models share the same source instance
+
+ // and both models share the same source instance
UserFactory.store === PostFactory.store; //=> true
```
- @method factoryInjection
+
+ @method factoryInjection
@param {String} factoryName
@param {String} property
@param {String} injectionName
*/
- factoryInjection: function (fullName, property, injectionName) {
+ factoryInjection: function(fullName, property, injectionName) {
var normalizedName = this.normalize(fullName);
var normalizedInjectionName = this.normalize(injectionName);
this.validateFullName(injectionName);
- if (fullName.indexOf(":") === -1) {
+ if (fullName.indexOf(':') === -1) {
return this.factoryTypeInjection(normalizedName, property, normalizedInjectionName);
}
@@ -2029,17 +2165,15 @@
});
},
- validateFullName: function (fullName) {
+ validateFullName: function(fullName) {
if (!VALID_FULL_NAME_REGEXP.test(fullName)) {
- throw new TypeError("Invalid Fullname, expected: `type:name` got: " + fullName);
+ throw new TypeError('Invalid Fullname, expected: `type:name` got: ' + fullName);
}
return true;
},
- validateInjections: function (injections) {
- if (!injections) {
- return;
- }
+ validateInjections: function(injections) {
+ if (!injections) { return; }
var fullName;
@@ -2047,12 +2181,12 @@
fullName = injections[i].fullName;
if (!this.has(fullName)) {
- throw new Error("Attempting to inject an unknown injection: `" + fullName + "`");
+ throw new Error('Attempting to inject an unknown injection: `' + fullName + '`');
}
}
},
- normalizeInjectionsHash: function (hash) {
+ normalizeInjectionsHash: function(hash) {
var injections = [];
for (var key in hash) {
@@ -2069,7 +2203,7 @@
return injections;
},
- getInjections: function (fullName) {
+ getInjections: function(fullName) {
var injections = this._injections[fullName] || [];
if (this.fallback) {
injections = injections.concat(this.fallback.getInjections(fullName));
@@ -2077,7 +2211,7 @@
return injections;
},
- getTypeInjections: function (type) {
+ getTypeInjections: function(type) {
var injections = this._typeInjections[type] || [];
if (this.fallback) {
injections = injections.concat(this.fallback.getTypeInjections(type));
@@ -2085,7 +2219,7 @@
return injections;
},
- getFactoryInjections: function (fullName) {
+ getFactoryInjections: function(fullName) {
var injections = this._factoryInjections[fullName] || [];
if (this.fallback) {
injections = injections.concat(this.fallback.getFactoryInjections(fullName));
@@ -2093,7 +2227,7 @@
return injections;
},
- getFactoryTypeInjections: function (type) {
+ getFactoryTypeInjections: function(type) {
var injections = this._factoryTypeInjections[type] || [];
if (this.fallback) {
injections = injections.concat(this.fallback.getFactoryTypeInjections(type));
@@ -2104,9 +2238,7 @@
function resolve(registry, normalizedName) {
var cached = registry._resolveCache[normalizedName];
- if (cached) {
- return cached;
- }
+ if (cached) { return cached; }
var resolved = registry.resolver(normalizedName) || registry.registrations[normalizedName];
registry._resolveCache[normalizedName] = resolved;
@@ -3191,13 +3323,13 @@
});
enifed('ember-application', ['ember-metal/core', 'ember-runtime/system/lazy_load', 'ember-application/system/resolver', 'ember-application/system/application', 'ember-application/ext/controller'], function (Ember, lazy_load, resolver, Application) {
- 'use strict';
+ 'use strict';
- Ember['default'].Application = Application['default'];
- Ember['default'].Resolver = resolver.Resolver;
- Ember['default'].DefaultResolver = resolver.DefaultResolver;
+ Ember['default'].Application = Application['default'];
+ Ember['default'].Resolver = resolver.Resolver;
+ Ember['default'].DefaultResolver = resolver["default"];
- lazy_load.runLoadHooks("Ember.Application", Application['default']);
+ lazy_load.runLoadHooks('Ember.Application', Application['default']);
});
enifed('ember-application/ext/controller', ['exports', 'ember-metal/core', 'ember-metal/property_get', 'ember-metal/error', 'ember-metal/utils', 'ember-metal/computed', 'ember-runtime/mixins/controller', 'ember-routing/system/controller_for'], function (exports, Ember, property_get, EmberError, utils, computed, ControllerMixin, controllerFor) {
@@ -3213,12 +3345,13 @@
var dependency, i, l;
var missing = [];
- for (i = 0, l = needs.length; i < l; i++) {
+ for (i=0, l=needs.length; i<l; i++) {
dependency = needs[i];
- Ember['default'].assert(utils.inspect(controller) + "#needs must not specify dependencies with periods in their names (" + dependency + ")", dependency.indexOf(".") === -1);
+ Ember['default'].assert(utils.inspect(controller) + "#needs must not specify dependencies with periods in their names (" +
+ dependency + ")", dependency.indexOf('.') === -1);
- if (dependency.indexOf(":") === -1) {
+ if (dependency.indexOf(':') === -1) {
dependency = "controller:" + dependency;
}
@@ -3228,28 +3361,34 @@
}
}
if (missing.length) {
- throw new EmberError['default'](utils.inspect(controller) + " needs [ " + missing.join(", ") + " ] but " + (missing.length > 1 ? "they" : "it") + " could not be found");
+ throw new EmberError['default'](utils.inspect(controller) + " needs [ " + missing.join(', ') +
+ " ] but " + (missing.length > 1 ? 'they' : 'it') + " could not be found");
}
}
- var defaultControllersComputedProperty = computed.computed(function () {
+ var defaultControllersComputedProperty = computed.computed(function() {
var controller = this;
return {
- needs: property_get.get(controller, "needs"),
- container: property_get.get(controller, "container"),
- unknownProperty: function (controllerName) {
+ needs: property_get.get(controller, 'needs'),
+ container: property_get.get(controller, 'container'),
+ unknownProperty: function(controllerName) {
var needs = this.needs;
var dependency, i, l;
- for (i = 0, l = needs.length; i < l; i++) {
+ for (i=0, l=needs.length; i<l; i++) {
dependency = needs[i];
if (dependency === controllerName) {
- return this.container.lookup("controller:" + controllerName);
+ return this.container.lookup('controller:' + controllerName);
}
}
- var errorMessage = utils.inspect(controller) + "#needs does not include `" + controllerName + "`. To access the " + controllerName + " controller from " + utils.inspect(controller) + ", " + utils.inspect(controller) + " should have a `needs` property that is an array of the controllers it has access to.";
+ var errorMessage = utils.inspect(controller) + '#needs does not include `' +
+ controllerName + '`. To access the ' +
+ controllerName + ' controller from ' +
+ utils.inspect(controller) + ', ' +
+ utils.inspect(controller) +
+ ' should have a `needs` property that is an array of the controllers it has access to.';
throw new ReferenceError(errorMessage);
},
setUnknownProperty: function (key, value) {
@@ -3263,58 +3402,73 @@
@namespace Ember
*/
ControllerMixin['default'].reopen({
- concatenatedProperties: ["needs"],
+ 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
+
+ For example, when you define a controller:
+
+ ```javascript
App.CommentsController = Ember.ArrayController.extend({
needs: ['post']
});
```
- The application's single instance of these other
+
+ The application's single instance of these other
controllers are accessible by name through the
`controllers` property:
- ```javascript
+
+ ```javascript
this.get('controllers.post'); // instance of App.PostController
```
- Given that you have a nested controller (nested resource):
- ```javascript
+
+ 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
+
+ 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
+
+ You will be able to get access to it:
+
+ ```javascript
this.get('controllers.commentsNew'); // instance of App.CommentsNewController
```
- This is only available for singleton controllers.
- @property {Array} needs
+
+ This is only available for singleton controllers.
+
+ @property {Array} needs
@default []
*/
needs: [],
- init: function () {
- var needs = property_get.get(this, "needs");
- var length = property_get.get(needs, "length");
+ init: function() {
+ var needs = property_get.get(this, 'needs');
+ var length = property_get.get(needs, 'length');
if (length > 0) {
- Ember['default'].assert(" `" + utils.inspect(this) + " specifies `needs`, but does " + "not have a container. Please ensure this controller was " + "instantiated with a container.", this.container || this.controllers !== defaultControllersComputedProperty);
+ Ember['default'].assert(' `' + utils.inspect(this) + ' specifies `needs`, but does ' +
+ "not have a container. Please ensure this controller was " +
+ "instantiated with a container.",
+ this.container || this.controllers !== defaultControllersComputedProperty);
if (this.container) {
verifyNeedsDependencies(this, this.container, needs);
}
// if needs then initialize controllers proxy
- property_get.get(this, "controllers");
+ property_get.get(this, 'controllers');
}
this._super.apply(this, arguments);
@@ -3325,16 +3479,17 @@
@see {Ember.Route#controllerFor}
@deprecated Use `needs` instead
*/
- controllerFor: function (controllerName) {
+ controllerFor: function(controllerName) {
Ember['default'].deprecate("Controller#controllerFor is deprecated, please use Controller#needs instead");
- return controllerFor['default'](property_get.get(this, "container"), controllerName);
+ return controllerFor['default'](property_get.get(this, 'container'), controllerName);
},
/**
Stores the instances of other controllers available from within
this controller. Any controller listed by name in the `needs`
property will be accessible by name through this property.
- ```javascript
+
+ ```javascript
App.CommentsController = Ember.ArrayController.extend({
needs: ['post'],
postTitle: function() {
@@ -3343,7 +3498,8 @@
}.property('controllers.post.title')
});
```
- @see {Ember.ControllerMixin#needs}
+
+ @see {Ember.ControllerMixin#needs}
@property {Object} controllers
@default null
*/
@@ -3367,31 +3523,36 @@
/**
The application instance's container. The container stores all of the
instance-specific state for this application run.
- @property {Ember.Container} container
+
+ @property {Ember.Container} container
*/
container: null,
/**
The application's registry. The registry contains the classes, templates,
and other code that makes up the application.
- @property {Ember.Registry} registry
+
+ @property {Ember.Registry} registry
*/
applicationRegistry: null,
/**
The registry for this application instance. It should use the
`applicationRegistry` as a fallback.
- @property {Ember.Registry} registry
+
+ @property {Ember.Registry} registry
*/
registry: null,
/**
The DOM events for which the event dispatcher should listen.
- By default, the application's `Ember.EventDispatcher` listens
+
+ 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
+
+ @private
@property {Object} customEvents
*/
customEvents: null,
@@ -3400,12 +3561,13 @@
The root DOM element of the Application as an element or a
[jQuery-compatible selector
string](http://api.jquery.com/category/selectors/).
- @private
+
+ @private
@property {String|DOMElement} rootElement
*/
rootElement: null,
- init: function () {
+ init: function() {
this._super.apply(this, arguments);
// Create a per-instance registry that will use the application's registry
@@ -3427,7 +3589,7 @@
// 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 });
+ this.registry.register('-application-instance:main', this, { instantiate: false });
},
/**
@@ -3435,16 +3597,15 @@
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
+
+ @param options
@private
*/
- setupRouter: function (options) {
- var router = this.container.lookup("router:main");
+ setupRouter: function(options) {
+ var router = this.container.lookup('router:main');
var location = options.location;
- if (location) {
- property_set.set(router, "location", location);
- }
+ if (location) { property_set.set(router, 'location', location); }
router._setupLocation();
router.setupRouter(true);
@@ -3454,13 +3615,15 @@
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
+
+ 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
+
+ @param view {Ember.View} the root-most view
@private
*/
- didCreateRootView: function (view) {
+ didCreateRootView: function(view) {
view.appendTo(this.rootElement);
},
@@ -3468,15 +3631,15 @@
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.
- Ensure that you have called `setupRouter()` on the instance before using
+
+ Ensure that you have called `setupRouter()` on the instance before using
this method.
- @private
+
+ @private
*/
- startRouting: function () {
- var router = this.container.lookup("router:main");
- if (!router) {
- return;
- }
+ startRouting: function() {
+ var router = this.container.lookup('router:main');
+ if (!router) { return; }
var isModuleBasedResolver = !!this.registry.resolver.moduleBasedResolver;
router.startRouting(isModuleBasedResolver);
@@ -3486,11 +3649,12 @@
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
+
+ @param url {String} the URL the router should route to
@private
*/
- handleURL: function (url) {
- var router = this.container.lookup("router:main");
+ handleURL: function(url) {
+ var router = this.container.lookup('router:main');
return router.handleURL(url);
},
@@ -3498,8 +3662,8 @@
/**
@private
*/
- setupEventDispatcher: function () {
- var dispatcher = this.container.lookup("event_dispatcher:main");
+ setupEventDispatcher: function() {
+ var dispatcher = this.container.lookup('event_dispatcher:main');
dispatcher.setup(this.customEvents, this.rootElement);
@@ -3509,9 +3673,9 @@
/**
@private
*/
- willDestroy: function () {
+ willDestroy: function() {
this._super.apply(this, arguments);
- run['default'](this.container, "destroy");
+ run['default'](this.container, 'destroy');
}
});
@@ -3684,23 +3848,28 @@
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,
+
+ 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
+
+ @property rootElement
@type DOMElement
@default 'body'
*/
- rootElement: "body",
+ rootElement: 'body',
/**
The `Ember.EventDispatcher` responsible for delegating events to this
application's views.
- The event dispatcher is created by the application at initialization time
+
+ 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
+
+ See the documentation for `Ember.EventDispatcher` for more information.
+
+ @property eventDispatcher
@type Ember.EventDispatcher
@default null
*/
@@ -3708,15 +3877,18 @@
/**
The DOM events for which the event dispatcher should listen.
- By default, the application's `Ember.EventDispatcher` listens
+
+ 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
+
+ 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
+
+ ```javascript
var App = Ember.Application.create({
customEvents: {
// add support for the paste event
@@ -3724,7 +3896,8 @@
}
});
```
- @property customEvents
+
+ @property customEvents
@type Object
@default null
*/
@@ -3736,14 +3909,15 @@
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
+
+ @property autoboot
@type Boolean
@default true
@private
*/
autoboot: true,
- init: function () {
+ init: function() {
this._super.apply(this, arguments);
if (!this.$) {
@@ -3767,11 +3941,12 @@
/**
Build and configure the registry for the current application.
- @private
+
+ @private
@method buildRegistry
@return {Ember.Registry} the configured registry
*/
- buildRegistry: function () {
+ buildRegistry: function() {
var registry = this.registry = Application.buildRegistry(this);
return registry;
@@ -3779,19 +3954,20 @@
/**
Create a container for the current application's registry.
- @private
+
+ @private
@method buildInstance
@return {Ember.Container} the configured container
*/
- buildInstance: function () {
+ buildInstance: function() {
return ApplicationInstance['default'].create({
- customEvents: property_get.get(this, "customEvents"),
- rootElement: property_get.get(this, "rootElement"),
+ customEvents: property_get.get(this, 'customEvents'),
+ rootElement: property_get.get(this, 'rootElement'),
applicationRegistry: this.registry
});
},
- buildDefaultInstance: function () {
+ buildDefaultInstance: function() {
var instance = this.buildInstance();
// TODO2.0: Legacy support for App.__container__
@@ -3806,43 +3982,52 @@
/**
Automatically initialize the application once the DOM has
become ready.
- The initialization itself is scheduled on the actions queue
+
+ 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
+
+ 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
+
+ @private
@method scheduleInitialize
*/
- waitForDOMReady: function (_instance) {
+ waitForDOMReady: function(_instance) {
if (!this.$ || this.$.isReady) {
- run['default'].schedule("actions", this, "domReady", _instance);
+ run['default'].schedule('actions', this, 'domReady', _instance);
} else {
- this.$().ready(run['default'].bind(this, "domReady", _instance));
+ this.$().ready(run['default'].bind(this, 'domReady', _instance));
}
},
/**
Use this to defer readiness until some condition is true.
- Example:
- ```javascript
+
+ Example:
+
+ ```javascript
var App = Ember.Application.create();
- App.deferReadiness();
+
+ 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
+
+ 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
+
+ However, if the setup requires a loading UI, it might be better
to use the router for this purpose.
- @method deferReadiness
+
+ @method deferReadiness
*/
- deferReadiness: function () {
+ deferReadiness: function() {
Ember['default'].assert("You must call deferReadiness on an instance of Ember.Application", this instanceof Application);
Ember['default'].assert("You cannot defer readiness since the `ready()` hook has already been called.", this._readinessDeferrals > 0);
this._readinessDeferrals++;
@@ -3852,10 +4037,11 @@
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
+
+ @method advanceReadiness
@see {Ember.Application#deferReadiness}
*/
- advanceReadiness: function () {
+ advanceReadiness: function() {
Ember['default'].assert("You must call advanceReadiness on an instance of Ember.Application", this instanceof Application);
this._readinessDeferrals--;
@@ -3868,137 +4054,162 @@
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
+
+ A simple example:
+
+ ```javascript
var App = Ember.Application.create();
- App.Orange = Ember.Object.extend();
+
+ App.Orange = Ember.Object.extend();
App.register('fruit:favorite', App.Orange);
```
- Ember will resolve factories from the `App` namespace automatically.
+
+ 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
+
+ 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,
+
+ 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`
+
+ 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
+
+ Some examples modifying that default behavior:
+
+ ```javascript
var App = Ember.Application.create();
- App.Person = Ember.Object.extend();
+
+ 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('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
+
+ @method register
@param fullName {String} type:name (e.g., 'model:user')
@param factory {Function} (e.g., App.Person)
@param options {Object} (optional) disable instantiation or singleton usage
**/
- register: function () {
+ register: function() {
this.registry.register.apply(this.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
+
+ 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
+
+ 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
+
+ // 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'
+
+ // 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({
+
+ App.IndexController = Ember.Controller.extend({
isLoggedIn: Ember.computed.alias('session.isAuthenticated')
});
```
- Injections can also be performed on specific factories.
- ```javascript
+
+ Injections can also be performed on specific factories.
+
+ ```javascript
App.inject(<full_name or type>, <property name>, <full_name>)
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
+
+ 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
+
+ **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
+
+ @method inject
@param factoryNameOrType {String}
@param property {String}
@param injectionName {String}
**/
- inject: function () {
+ inject: function() {
this.registry.injection.apply(this.registry, arguments);
},
/**
Calling initialize manually is not supported.
- Please see Ember.Application#advanceReadiness and
+
+ Please see Ember.Application#advanceReadiness and
Ember.Application#deferReadiness.
- @private
+
+ @private
@deprecated
@method initialize
**/
- initialize: function () {
- Ember['default'].deprecate("Calling initialize manually is not supported. Please see Ember.Application#advanceReadiness and Ember.Application#deferReadiness");
+ initialize: function() {
+ Ember['default'].deprecate('Calling initialize manually is not supported. Please see Ember.Application#advanceReadiness and Ember.Application#deferReadiness');
},
/**
Initialize the application. This happens automatically.
- Run any initializers and run the application load hook. These hooks may
+
+ 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
+
+ @private
@method _initialize
*/
- domReady: function (_instance) {
- if (this.isDestroyed) {
- return;
- }
+ domReady: function(_instance) {
+ if (this.isDestroyed) { return; }
var app = this;
- this.boot().then(function () {
+ this.boot().then(function() {
app.runInstanceInitializers(_instance);
});
return this;
},
- boot: function () {
- if (this._bootPromise) {
- return this._bootPromise;
- }
+ boot: function() {
+ if (this._bootPromise) { return this._bootPromise; }
var defer = new Ember['default'].RSVP.defer();
this._bootPromise = defer.promise;
this._bootResolver = defer;
this.runInitializers(this.registry);
- lazy_load.runLoadHooks("application", this);
+ lazy_load.runLoadHooks('application', this);
this.advanceReadiness();
@@ -4008,38 +4219,50 @@
/**
Reset the application. This is typically used only in tests. It cleans up
the application in the following order:
- 1. Deactivate existing routes
+
+ 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
+
+ Typical Example:
+
+ ```javascript
var App;
- run(function() {
+
+ run(function() {
App = Ember.Application.create();
});
- module('acceptance test', {
+
+ module('acceptance test', {
setup: function() {
App.reset();
}
});
- test('first test', function() {
+
+ test('first test', function() {
// App is freshly reset
});
- test('second test', function() {
+
+ test('second test', function() {
// App is again freshly reset
});
```
- Advanced Example:
- Occasionally you may want to prevent the app from initializing during
+
+ 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
+
+ ```javascript
var App;
- run(function() {
+
+ run(function() {
App = Ember.Application.create();
});
- module('acceptance test', {
+
+ module('acceptance test', {
setup: function() {
run(function() {
App.reset();
@@ -4047,17 +4270,21 @@
});
}
});
- test('first test', function() {
+
+ test('first test', function() {
ok(true, 'something before app is initialized');
- run(function() {
+
+ run(function() {
App.advanceReadiness();
});
- ok(true, 'something after app is initialized');
+
+ ok(true, 'something after app is initialized');
});
```
- @method reset
+
+ @method reset
**/
- reset: function () {
+ reset: function() {
var instance = this.__deprecatedInstance__;
this._readinessDeferrals = 1;
@@ -4065,11 +4292,11 @@
this._bootResolver = null;
function handleReset() {
- run['default'](instance, "destroy");
+ run['default'](instance, 'destroy');
this.buildDefaultInstance();
- run['default'].schedule("actions", this, "domReady");
+ run['default'].schedule('actions', this, 'domReady');
}
run['default'].join(this, handleReset);
@@ -4079,9 +4306,9 @@
@private
@method runInitializers
*/
- runInitializers: function (registry) {
+ runInitializers: function(registry) {
var App = this;
- this._runInitializer("initializers", function (name, initializer) {
+ this._runInitializer('initializers', function(name, initializer) {
Ember['default'].assert("No application initializer named '" + name + "'", !!initializer);
@@ -4091,14 +4318,14 @@
});
},
- runInstanceInitializers: function (instance) {
- this._runInitializer("instanceInitializers", function (name, initializer) {
+ runInstanceInitializers: function(instance) {
+ this._runInitializer('instanceInitializers', function(name, initializer) {
Ember['default'].assert("No instance initializer named '" + name + "'", !!initializer);
initializer.initialize(instance);
});
},
- _runInitializer: function (bucketName, cb) {
+ _runInitializer: function(bucketName, cb) {
var initializersByName = property_get.get(this.constructor, bucketName);
var initializers = props(initializersByName);
var graph = new DAG['default']();
@@ -4118,7 +4345,7 @@
@private
@method didBecomeReady
*/
- didBecomeReady: function () {
+ didBecomeReady: function() {
if (this.autoboot) {
if (environment['default'].hasDOM) {
this.__deprecatedInstance__.setupEventDispatcher();
@@ -4142,34 +4369,36 @@
/**
Called when the Application has become ready.
The call will be delayed until the DOM has become ready.
- @event ready
+
+ @event ready
*/
- ready: function () {
- return this;
- },
+ ready: function() { return this; },
/**
@deprecated Use 'Resolver' instead
Set this to provide an alternate class to `Ember.DefaultResolver`
- @property resolver
+
+
+ @property resolver
*/
resolver: null,
/**
Set this to provide an alternate class to `Ember.DefaultResolver`
- @property resolver
+
+ @property resolver
*/
Resolver: null,
// This method must be moved to the application instance object
- willDestroy: function () {
+ willDestroy: function() {
Ember['default'].BOOTED = false;
this._bootPromise = null;
this._bootResolver = null;
this.__deprecatedInstance__.destroy();
},
- initializer: function (options) {
+ initializer: function(options) {
this.constructor.initializer(options);
},
@@ -4178,8 +4407,12 @@
@private
@deprecated
*/
- then: function () {
- Ember['default'].deprecate("Do not use `.then` on an instance of Ember.Application. Please use the `.ready` hook instead.", false, { url: "http://emberjs.com/guides/deprecations/#toc_code-then-code-on-ember-application" });
+ then: function() {
+ Ember['default'].deprecate(
+ 'Do not use `.then` on an instance of Ember.Application. Please use the `.ready` hook instead.',
+ false,
+ { url: 'http://emberjs.com/guides/deprecations/#toc_code-then-code-on-ember-application' }
+ );
this._super.apply(this, arguments);
}
@@ -4195,102 +4428,133 @@
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.
+
+ * `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
+
+ ```javascript
Ember.Application.initializer({
name: 'namedInitializer',
- initialize: function(container, application) {
+
+ initialize: function(container, application) {
Ember.debug('Running namedInitializer!');
}
});
```
- * `before` and `after` are used to ensure that this initializer is ran prior
+
+ * `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
+
+ An example of ordering initializers, we create an initializer named `first`:
+
+ ```javascript
Ember.Application.initializer({
name: 'first',
- initialize: function(container, application) {
+
+ initialize: function(container, application) {
Ember.debug('First initializer!');
}
});
- // DEBUG: First initializer!
+
+ // DEBUG: First initializer!
```
- We add another initializer named `second`, specifying that it should run
+
+ We add another initializer named `second`, specifying that it should run
after the initializer named `first`:
- ```javascript
+
+ ```javascript
Ember.Application.initializer({
name: 'second',
after: 'first',
- initialize: function(container, application) {
+
+ initialize: function(container, application) {
Ember.debug('Second initializer!');
}
});
- // DEBUG: First initializer!
+
+ // DEBUG: First initializer!
// DEBUG: Second initializer!
```
- Afterwards we add a further initializer named `pre`, this time specifying
+
+ Afterwards we add a further initializer named `pre`, this time specifying
that it should run before the initializer named `first`:
- ```javascript
+
+ ```javascript
Ember.Application.initializer({
name: 'pre',
before: 'first',
- initialize: function(container, application) {
+
+ initialize: function(container, application) {
Ember.debug('Pre initializer!');
}
});
- // DEBUG: Pre initializer!
+
+ // DEBUG: Pre initializer!
// DEBUG: First initializer!
// DEBUG: Second initializer!
```
- Finally we add an initializer named `post`, specifying it should run after
+
+ Finally we add an initializer named `post`, specifying it should run after
both the `first` and the `second` initializers:
- ```javascript
+
+ ```javascript
Ember.Application.initializer({
name: 'post',
after: ['first', 'second'],
- initialize: function(container, application) {
+
+ initialize: function(container, application) {
Ember.debug('Post initializer!');
}
});
- // DEBUG: Pre initializer!
+
+ // DEBUG: Pre initializer!
// DEBUG: First initializer!
// DEBUG: Second initializer!
// DEBUG: Post initializer!
```
- * `initialize` is a callback function that receives two arguments, `container`
+
+ * `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
+
+ Example of using `container` to preload data into the store:
+
+ ```javascript
Ember.Application.initializer({
name: 'preload-data',
- initialize: function(container, application) {
+
+ initialize: function(container, application) {
var store = container.lookup('store:main');
- store.pushPayload(preloadedData);
+
+ store.pushPayload(preloadedData);
}
});
```
- Example of using `application` to register an adapter:
- ```javascript
+
+ Example of using `application` to register an adapter:
+
+ ```javascript
Ember.Application.initializer({
name: 'api-adapter',
- initialize: function(container, application) {
+
+ initialize: function(container, application) {
application.register('api-adapter:main', ApiAdapter);
}
});
```
- @method initializer
+
+ @method initializer
@param initializer {Object}
*/
- initializer: buildInitializerMethod("initializers", "initializer"),
+ 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
+
+ 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.
@@ -4302,14 +4566,15 @@
`controller` property
* the application view receives the application template as its
`defaultTemplate` property
- @private
+
+ @private
@method buildRegistry
@static
@param {Ember.Application} namespace the application for which to
build the registry
@return {Ember.Registry} the built registry
*/
- buildRegistry: function (namespace) {
+ buildRegistry: function(namespace) {
var registry = new Registry['default']();
registry.set = property_set.set;
@@ -4318,57 +4583,55 @@
registry.describe = registry.resolver.describe;
registry.makeToString = registry.resolver.makeToString;
- registry.optionsForType("component", { singleton: false });
- registry.optionsForType("view", { singleton: false });
- registry.optionsForType("template", { instantiate: false });
- registry.optionsForType("helper", { instantiate: false });
+ registry.optionsForType('component', { singleton: false });
+ registry.optionsForType('view', { singleton: false });
+ registry.optionsForType('template', { instantiate: false });
+ registry.optionsForType('helper', { instantiate: false });
- registry.register("application:main", namespace, { instantiate: false });
+ registry.register('application:main', namespace, { instantiate: false });
- registry.register("controller:basic", Controller['default'], { instantiate: false });
- registry.register("controller:object", ObjectController['default'], { instantiate: false });
- registry.register("controller:array", ArrayController['default'], { instantiate: false });
+ registry.register('controller:basic', Controller['default'], { instantiate: false });
+ registry.register('controller:object', ObjectController['default'], { instantiate: false });
+ registry.register('controller:array', ArrayController['default'], { instantiate: false });
- registry.register("renderer:-dom", { create: function () {
- return new Renderer['default'](new DOMHelper['default']());
- } });
+ registry.register('renderer:-dom', { create: function() { return new Renderer['default'](new DOMHelper['default']()); } });
- registry.injection("view", "renderer", "renderer:-dom");
- registry.register("view:select", SelectView['default']);
- registry.register("view:-outlet", outlet.OutletView);
+ registry.injection('view', 'renderer', 'renderer:-dom');
+ registry.register('view:select', SelectView['default']);
+ registry.register('view:-outlet', outlet.OutletView);
- registry.register("view:default", _MetamorphView['default']);
- registry.register("view:toplevel", EmberView['default'].extend());
+ registry.register('view:default', _MetamorphView['default']);
+ registry.register('view:toplevel', EmberView['default'].extend());
- registry.register("route:basic", Route['default'], { instantiate: false });
- registry.register("event_dispatcher:main", EventDispatcher['default']);
+ registry.register('route:basic', Route['default'], { instantiate: false });
+ registry.register('event_dispatcher:main', EventDispatcher['default']);
- registry.injection("router:main", "namespace", "application:main");
- registry.injection("view:-outlet", "namespace", "application:main");
+ registry.injection('router:main', 'namespace', 'application:main');
+ registry.injection('view:-outlet', 'namespace', 'application:main');
- registry.register("location:auto", AutoLocation['default']);
- registry.register("location:hash", HashLocation['default']);
- registry.register("location:history", HistoryLocation['default']);
- registry.register("location:none", NoneLocation['default']);
+ registry.register('location:auto', AutoLocation['default']);
+ registry.register('location:hash', HashLocation['default']);
+ registry.register('location:history', HistoryLocation['default']);
+ registry.register('location:none', NoneLocation['default']);
- registry.injection("controller", "target", "router:main");
- registry.injection("controller", "namespace", "application:main");
+ registry.injection('controller', 'target', 'router:main');
+ registry.injection('controller', 'namespace', 'application:main');
- registry.register("-bucket-cache:main", BucketCache['default']);
- registry.injection("router", "_bucketCache", "-bucket-cache:main");
- registry.injection("route", "_bucketCache", "-bucket-cache:main");
- registry.injection("controller", "_bucketCache", "-bucket-cache:main");
+ registry.register('-bucket-cache:main', BucketCache['default']);
+ registry.injection('router', '_bucketCache', '-bucket-cache:main');
+ registry.injection('route', '_bucketCache', '-bucket-cache:main');
+ registry.injection('controller', '_bucketCache', '-bucket-cache:main');
- registry.injection("route", "router", "router:main");
- registry.injection("location", "rootURL", "-location-setting:root-url");
+ registry.injection('route', 'router', 'router:main');
+ registry.injection('location', 'rootURL', '-location-setting:root-url');
// 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");
+ registry.register('resolver-for-debugging:main', registry.resolver.__resolver__, { instantiate: false });
+ registry.injection('container-debug-adapter:main', 'resolver', 'resolver-for-debugging:main');
+ registry.injection('data-adapter:main', 'containerDebugAdapter', 'container-debug-adapter:main');
// Custom resolver authors may want to register their own ContainerDebugAdapter with this key
- registry.register("container-debug-adapter:main", ContainerDebugAdapter['default']);
+ registry.register('container-debug-adapter:main', ContainerDebugAdapter['default']);
return registry;
}
@@ -4391,9 +4654,12 @@
@return {*} the resolved value for a given lookup
*/
function resolverFor(namespace) {
- Ember['default'].deprecate("Application.resolver is deprecated in favor of Application.Resolver", !namespace.get("resolver"));
+ Ember['default'].deprecate(
+ 'Application.resolver is deprecated in favor of Application.Resolver',
+ !namespace.get('resolver')
+ );
- var ResolverClass = namespace.get("resolver") || namespace.get("Resolver") || DefaultResolver['default'];
+ var ResolverClass = namespace.get('resolver') || namespace.get('Resolver') || DefaultResolver['default'];
var resolver = ResolverClass.create({
namespace: namespace
});
@@ -4402,19 +4668,19 @@
return resolver.resolve(fullName);
}
- resolve.describe = function (fullName) {
+ resolve.describe = function(fullName) {
return resolver.lookupDescription(fullName);
};
- resolve.makeToString = function (factory, fullName) {
+ resolve.makeToString = function(factory, fullName) {
return resolver.makeToString(factory, fullName);
};
- resolve.normalize = function (fullName) {
+ resolve.normalize = function(fullName) {
if (resolver.normalize) {
return resolver.normalize(fullName);
} else {
- Ember['default'].deprecate("The Resolver should now provide a 'normalize' function");
+ Ember['default'].deprecate('The Resolver should now provide a \'normalize\' function');
return fullName;
}
};
@@ -4429,7 +4695,7 @@
librariesRegistered = true;
if (environment['default'].hasDOM) {
- Ember['default'].libraries.registerCoreLibrary("jQuery", jQuery['default']().jquery);
+ Ember['default'].libraries.registerCoreLibrary('jQuery', jQuery['default']().jquery);
}
}
}
@@ -4440,24 +4706,24 @@
Ember['default'].LOG_VERSION = false;
var libs = Ember['default'].libraries._registry;
- var nameLengths = EnumerableUtils['default'].map(libs, function (item) {
- return property_get.get(item, "name.length");
+ var nameLengths = EnumerableUtils['default'].map(libs, function(item) {
+ return property_get.get(item, 'name.length');
});
var maxNameLength = Math.max.apply(this, nameLengths);
- Ember['default'].debug("-------------------------------");
+ Ember['default'].debug('-------------------------------');
for (var i = 0, l = libs.length; i < l; i++) {
var lib = libs[i];
- var spaces = new Array(maxNameLength - lib.name.length + 1).join(" ");
- Ember['default'].debug([lib.name, spaces, " : ", lib.version].join(""));
+ var spaces = new Array(maxNameLength - lib.name.length + 1).join(' ');
+ Ember['default'].debug([lib.name, spaces, ' : ', lib.version].join(''));
}
- Ember['default'].debug("-------------------------------");
+ Ember['default'].debug('-------------------------------');
}
}
function buildInitializerMethod(bucketName, humanName) {
- return function (initializer) {
+ 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
@@ -4469,7 +4735,7 @@
}
Ember['default'].assert("The " + humanName + " '" + initializer.name + "' has already been registered", !this[bucketName][initializer.name]);
- Ember['default'].assert("An " + humanName + " cannot be registered without an initialize function", utils.canInvoke(initializer, "initialize"));
+ Ember['default'].assert("An " + humanName + " cannot be registered without an initialize function", utils.canInvoke(initializer, 'initialize'));
Ember['default'].assert("An " + humanName + " cannot be registered without a name property", initializer.name !== undefined);
this[bucketName][initializer.name] = initializer;
@@ -4492,66 +4758,142 @@
/**
This will be set to the Application instance when it is
created.
- @property namespace
+
+ @property namespace
*/
namespace: null,
- normalize: Ember['default'].required(Function),
- resolve: Ember['default'].required(Function),
- parseName: Ember['default'].required(Function),
+ normalize: Ember['default'].required(Function),
+ resolve: Ember['default'].required(Function),
+ parseName: Ember['default'].required(Function),
lookupDescription: Ember['default'].required(Function),
- makeToString: Ember['default'].required(Function),
- resolveOther: Ember['default'].required(Function),
- _logLookup: Ember['default'].required(Function)
+ makeToString: Ember['default'].required(Function),
+ resolveOther: Ember['default'].required(Function),
+ _logLookup: Ember['default'].required(Function)
});
+ /**
+ 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
+ */
exports['default'] = EmberObject['default'].extend({
/**
This will be set to the Application instance when it is
created.
- @property namespace
+
+ @property namespace
*/
namespace: null,
- init: function () {
+ init: function() {
this._parseNameCache = dictionary['default'](null);
},
- normalize: function (fullName) {
- var split = fullName.split(":", 2);
+ normalize: function(fullName) {
+ var split = fullName.split(':', 2);
var type = split[0];
var name = split[1];
- Ember['default'].assert("Tried to normalize a container name without a colon (:) in it." + " You probably tried to lookup a name that did not contain a type," + " a colon, and a name. A proper lookup name would be `view:post`.", split.length === 2);
+ Ember['default'].assert("Tried to normalize a container name without a colon (:) in it." +
+ " You probably tried to lookup a name that did not contain a type," +
+ " a colon, and a name. A proper lookup name would be `view:post`.", split.length === 2);
- if (type !== "template") {
+ if (type !== 'template') {
var result = name;
- if (result.indexOf(".") > -1) {
- result = result.replace(/\.(.)/g, function (m) {
+ 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) {
+ if (name.indexOf('_') > -1) {
+ result = result.replace(/_(.)/g, function(m) {
return m.charAt(1).toUpperCase();
});
}
- return type + ":" + result;
+ 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
+
+ @method resolve
@param {String} fullName the lookup string
@return {Object} the resolved factory
*/
- resolve: function (fullName) {
+ resolve: function(fullName) {
var parsedName = this.parseName(fullName);
var resolveMethodName = parsedName.resolveMethodName;
var resolved;
@@ -4573,36 +4915,41 @@
Convert the string name of the form 'type:name' to
a Javascript object with the parsed aspects of the name
broken out.
- @protected
+
+ @protected
@param {String} fullName the lookup string
@method parseName
*/
- parseName: function (fullName) {
- return this._parseNameCache[fullName] || (this._parseNameCache[fullName] = this._parseName(fullName));
+ parseName: function(fullName) {
+ return this._parseNameCache[fullName] || (
+ this._parseNameCache[fullName] = this._parseName(fullName)
+ );
},
- _parseName: function (fullName) {
- var nameParts = fullName.split(":");
+ _parseName: function(fullName) {
+ var nameParts = fullName.split(':');
var type = nameParts[0];
var fullNameWithoutType = nameParts[1];
var name = fullNameWithoutType;
- var namespace = property_get.get(this, "namespace");
+ var namespace = property_get.get(this, 'namespace');
var root = namespace;
- if (type !== "template" && name.indexOf("/") !== -1) {
- var parts = name.split("/");
+ if (type !== 'template' && name.indexOf('/') !== -1) {
+ var parts = name.split('/');
name = parts[parts.length - 1];
- var namespaceName = string.capitalize(parts.slice(0, -1).join("."));
+ var namespaceName = string.capitalize(parts.slice(0, -1).join('.'));
root = Namespace['default'].byName(namespaceName);
- Ember['default'].assert("You are looking for a " + name + " " + type + " in the " + namespaceName + " namespace, but the namespace could not be found", root);
+ Ember['default'].assert('You are looking for a ' + name + ' ' + type +
+ ' in the ' + namespaceName +
+ ' namespace, but the namespace could not be found', root);
}
- var resolveMethodName = fullNameWithoutType === "main" ? "Main" : string.classify(type);
+ var resolveMethodName = fullNameWithoutType === 'main' ? 'Main' : string.classify(type);
if (!(name && type)) {
- throw new TypeError("Invalid fullName: `" + fullName + "`, must be of the form `type:name` ");
+ throw new TypeError('Invalid fullName: `' + fullName + '`, must be of the form `type:name` ');
}
return {
@@ -4611,7 +4958,7 @@
fullNameWithoutType: fullNameWithoutType,
name: name,
root: root,
- resolveMethodName: "resolve" + resolveMethodName
+ resolveMethodName: 'resolve' + resolveMethodName
};
},
@@ -4620,54 +4967,57 @@
Application namespace in assertions to describe the
precise name of the class that Ember is looking for, rather than
container keys.
- @protected
+
+ @protected
@param {String} fullName the lookup string
@method lookupDescription
*/
- lookupDescription: function (fullName) {
+ lookupDescription: function(fullName) {
var parsedName = this.parseName(fullName);
var description;
- if (parsedName.type === "template") {
- return "template at " + parsedName.fullNameWithoutType.replace(/\./g, "/");
+ if (parsedName.type === 'template') {
+ return 'template at ' + parsedName.fullNameWithoutType.replace(/\./g, '/');
}
- description = parsedName.root + "." + string.classify(parsedName.name).replace(/\./g, "");
+ description = parsedName.root + '.' + string.classify(parsedName.name).replace(/\./g, '');
- if (parsedName.type !== "model") {
+ if (parsedName.type !== 'model') {
description += string.classify(parsedName.type);
}
return description;
},
- makeToString: function (factory, fullName) {
+ makeToString: function(factory, fullName) {
return factory.toString();
},
/**
Given a parseName object (output from `parseName`), apply
the conventions expected by `Ember.Router`
- @protected
+
+ @protected
@param {Object} parsedName a parseName object with the parsed
fullName lookup string
@method useRouterNaming
*/
- useRouterNaming: function (parsedName) {
- parsedName.name = parsedName.name.replace(/\./g, "_");
- if (parsedName.name === "basic") {
- parsedName.name = "";
+ useRouterNaming: function(parsedName) {
+ parsedName.name = parsedName.name.replace(/\./g, '_');
+ if (parsedName.name === 'basic') {
+ parsedName.name = '';
}
},
/**
Look up the template in Ember.TEMPLATES
- @protected
+
+ @protected
@param {Object} parsedName a parseName object with the parsed
fullName lookup string
@method resolveTemplate
*/
- resolveTemplate: function (parsedName) {
- var templateName = parsedName.fullNameWithoutType.replace(/\./g, "/");
+ resolveTemplate: function(parsedName) {
+ var templateName = parsedName.fullNameWithoutType.replace(/\./g, '/');
if (Ember['default'].TEMPLATES[templateName]) {
return Ember['default'].TEMPLATES[templateName];
@@ -4681,82 +5031,84 @@
/**
Lookup the view using `resolveOther`
- @protected
+
+ @protected
@param {Object} parsedName a parseName object with the parsed
fullName lookup string
@method resolveView
*/
- resolveView: function (parsedName) {
+ resolveView: function(parsedName) {
this.useRouterNaming(parsedName);
return this.resolveOther(parsedName);
},
/**
Lookup the controller using `resolveOther`
- @protected
+
+ @protected
@param {Object} parsedName a parseName object with the parsed
fullName lookup string
@method resolveController
*/
- resolveController: function (parsedName) {
+ resolveController: function(parsedName) {
this.useRouterNaming(parsedName);
return this.resolveOther(parsedName);
},
/**
Lookup the route using `resolveOther`
- @protected
+
+ @protected
@param {Object} parsedName a parseName object with the parsed
fullName lookup string
@method resolveRoute
*/
- resolveRoute: function (parsedName) {
+ resolveRoute: function(parsedName) {
this.useRouterNaming(parsedName);
return this.resolveOther(parsedName);
},
/**
Lookup the model on the Application namespace
- @protected
+
+ @protected
@param {Object} parsedName a parseName object with the parsed