ember-source
- Version 6.1.0
- Published
- 8.61 MB
- 42 dependencies
- MIT license
Install
npm i ember-source
yarn add ember-source
pnpm add ember-source
Overview
A JavaScript framework for creating ambitious web applications
Index
Namespaces
@ember/-internals/glimmer
- BootEnvironment
- Component
- Component
- escapeExpression()
- FunctionBasedHelper
- FunctionBasedHelperInstance
- getTemplate()
- getTemplates()
- hasTemplate()
- helper()
- Helper
- Helper
- htmlSafe()
- Input
- Input
- isHTMLSafe()
- LinkTo
- LinkTo
- OutletState
- OutletView
- Renderer
- renderSettled()
- RenderState
- RootTemplate
- SafeString
- setComponentManager()
- setTemplate()
- setTemplates()
- setupApplicationRegistry()
- setupEngineRegistry()
- TemplatesRegistry
- Textarea
- Textarea
- uniqueId()
@ember/-internals/metal
- activateObserver()
- addArrayObserver()
- addListener()
- addNamespace()
- addObserver()
- alias()
- arrayContentDidChange()
- arrayContentWillChange()
- ASYNC_OBSERVERS
- autoComputed()
- beginPropertyChanges()
- cached
- changeProperties()
- computed()
- ComputedDecorator
- ComputedDescriptor
- ComputedProperty
- ComputedPropertyCallback
- ComputedPropertyGetter
- ComputedPropertyObj
- ComputedPropertySetter
- DEBUG_INJECTION_FUNCTIONS
- DecoratorPropertyDescriptor
- defineDecorator()
- defineProperty()
- defineValue()
- deprecateProperty()
- descriptorForDecorator()
- descriptorForProperty()
- eachProxyArrayDidChange()
- eachProxyArrayWillChange()
- ElementDescriptor
- endPropertyChanges()
- expandProperties()
- ExtendedMethodDecorator
- findNamespace()
- findNamespaces()
- flushAsyncObservers()
- get()
- getCachedValueFor()
- getProperties()
- hasListeners()
- hasUnknownProperty()
- HasUnknownProperty
- inject()
- isClassicDecorator()
- isComputed()
- isElementDescriptor()
- isNamespaceSearchDisabled()
- libraries
- Libraries
- makeComputedDecorator()
- markObjectAsDirty()
- NAMESPACES
- NAMESPACES_BY_ID
- nativeDescDecorator()
- notifyPropertyChange()
- objectAt()
- on()
- processAllNamespaces()
- processNamespace()
- PROPERTY_DID_CHANGE
- PropertyDidChange
- PROXY_CONTENT
- removeArrayObserver()
- removeListener()
- removeNamespace()
- removeObserver()
- replace()
- replaceInNativeArray()
- revalidateObservers()
- sendEvent()
- set()
- setClassicDecorator()
- setNamespaceSearchDisabled()
- setProperties()
- setUnprocessedMixins()
- SYNC_OBSERVERS
- tagForObject()
- tagForProperty()
- tracked()
- TrackedDescriptor
- trySet()
@ember/-internals/utils
- Cache
- canInvoke()
- checkHasSuper()
- dictionary()
- enumerableSymbol()
- generateGuid()
- getDebugName
- getName()
- GUID_KEY
- guidFor()
- intern()
- isInternalSymbol()
- isObject()
- isProxy()
- lookupDescriptor()
- observerListenerMetaFor()
- ROOT()
- setListeners()
- setName()
- setObservers()
- setProxy()
- setupMandatorySetter
- setWithMandatorySetter
- symbol
- teardownMandatorySetter
- toString()
- uuid()
- wrap()
@ember/-internals/views
- ActionManager()
- ActionSupport
- ActionSupport
- addChildView()
- ChildViewsSupport
- ChildViewsSupport
- ClassNamesSupport
- ClassNamesSupport
- clearElementView()
- clearViewElement()
- ComponentLookup
- constructStyleDeprecationMessage()
- CoreView
- CoreView
- EventDispatcher
- getChildViews()
- getElementView()
- getRootViews()
- getViewBoundingClientRect()
- getViewBounds()
- getViewClientRects()
- getViewElement()
- getViewId()
- isSimpleClick()
- MUTABLE_CELL
- setElementView()
- setViewElement()
- ViewMixin
- ViewMixin
- ViewStateSupport
- ViewStateSupport
@ember/-internals/views/lib/system/utils
- addChildView()
- clearElementView()
- clearViewElement()
- collectChildViews()
- constructStyleDeprecationMessage()
- contains()
- elMatches
- getChildViews()
- getElementView()
- getRootViews()
- getViewBoundingClientRect()
- getViewBounds()
- getViewClientRects()
- getViewElement()
- getViewId()
- getViewRange()
- initChildViews()
- isSimpleClick()
- matches()
- setElementView()
- setViewElement()
@ember/debug
- assert
- captureRenderTree()
- debug
- debugFreeze
- DebugFreezeFunc
- DebugFunc
- DebugFunctionType
- debugSeal
- DebugSealFunc
- deprecate()
- deprecateFunc
- DeprecateFuncFunc
- DeprecationOptions
- getDebugFunction
- GetDebugFunction
- info
- InfoFunc
- inspect()
- isTesting()
- registerDeprecationHandler()
- registerWarnHandler
- runInDebug
- RunInDebugFunc
- setDebugFunction
- SetDebugFunction
- setTesting()
- warn
ember.Ember
- A()
- ActionHandler
- ActionHandler
- addListener
- addObserver
- Application
- Application
- ApplicationInstance
- ApplicationInstance
- Array
- Array
- ArrayProxy
- ArrayProxy
- assert
- beginPropertyChanges
- BOOTED
- cacheFor
- canInvoke
- changeProperties
- Comparable
- Comparable
- compare
- Component
- Component
- ComponentLookup
- computed
- ComputedProperty
- ComputedProperty
- Container
- Container
- ContainerDebugAdapter
- ContainerDebugAdapter
- Controller
- Controller
- controllerFor
- ControllerMixin
- ControllerMixin
- CoreObject
- CoreObject
- DataAdapter
- DataAdapter
- debug
- Debug
- defineProperty
- deprecate
- deprecateFunc
- destroy
- endPropertyChanges
- Engine
- Engine
- EngineInstance
- EngineInstance
- Enumerable
- Enumerable
- ENV
- EventDispatcher
- Evented
- Evented
- expandProperties
- FEATURES
- generateController
- generateControllerFactory
- generateGuid
- get
- getOwner()
- getProperties
- GUID_KEY
- guidFor
- Handlebars
- HashLocation
- HashLocation
- hasListeners
- Helper
- Helper
- HistoryLocation
- HistoryLocation
- HTMLBars
- inject()
- inspect
- instrument
- Instrumentation
- isArray
- isBlank
- isEmpty
- isEqual
- isNamespace
- isNone
- isPresent
- libraries
- lookup
- makeArray
- meta
- mixin
- Mixin
- Mixin
- MutableArray
- MutableArray
- MutableEnumerable
- MutableEnumerable
- Namespace
- Namespace
- NativeArray
- NativeArray
- NoneLocation
- NoneLocation
- notifyPropertyChange
- Object
- Object
- ObjectProxy
- ObjectProxy
- Observable
- Observable
- observer
- on
- onerror
- onLoad
- PromiseProxyMixin
- PromiseProxyMixin
- Registry
- Registry
- removeListener
- removeObserver
- Route
- Route
- Router
- Router
- RouterDSL
- RouterDSL
- run
- runInDebug
- runLoadHooks
- sendEvent
- Service
- Service
- set
- setOwner
- setProperties
- setupForTesting
- subscribe
- TEMPLATES
- Test
- testing
- toString()
- trySet
- typeOf
- uuid
- VERSION
- ViewUtils
- warn
- wrap
ember/barrel.Ember
- A()
- ActionHandler
- ActionHandler
- addListener
- addObserver
- Application
- Application
- ApplicationInstance
- ApplicationInstance
- Array
- Array
- ArrayProxy
- ArrayProxy
- assert
- beginPropertyChanges
- BOOTED
- cacheFor
- canInvoke
- changeProperties
- Comparable
- Comparable
- compare
- Component
- Component
- ComponentLookup
- computed
- ComputedProperty
- ComputedProperty
- Container
- Container
- ContainerDebugAdapter
- ContainerDebugAdapter
- Controller
- Controller
- controllerFor
- ControllerMixin
- ControllerMixin
- CoreObject
- CoreObject
- DataAdapter
- DataAdapter
- debug
- Debug
- defineProperty
- deprecate
- deprecateFunc
- destroy
- endPropertyChanges
- Engine
- Engine
- EngineInstance
- EngineInstance
- Enumerable
- Enumerable
- ENV
- EventDispatcher
- Evented
- Evented
- expandProperties
- FEATURES
- generateController
- generateControllerFactory
- generateGuid
- get
- getOwner()
- getProperties
- GUID_KEY
- guidFor
- Handlebars
- HashLocation
- HashLocation
- hasListeners
- Helper
- Helper
- HistoryLocation
- HistoryLocation
- HTMLBars
- inject()
- inspect
- instrument
- Instrumentation
- isArray
- isBlank
- isEmpty
- isEqual
- isNamespace
- isNone
- isPresent
- libraries
- lookup
- makeArray
- meta
- mixin
- Mixin
- Mixin
- MutableArray
- MutableArray
- MutableEnumerable
- MutableEnumerable
- Namespace
- Namespace
- NativeArray
- NativeArray
- NoneLocation
- NoneLocation
- notifyPropertyChange
- Object
- Object
- ObjectProxy
- ObjectProxy
- Observable
- Observable
- observer
- on
- onerror
- onLoad
- PromiseProxyMixin
- PromiseProxyMixin
- Registry
- Registry
- removeListener
- removeObserver
- Route
- Route
- Router
- Router
- RouterDSL
- RouterDSL
- run
- runInDebug
- runLoadHooks
- sendEvent
- Service
- Service
- set
- setOwner
- setProperties
- setupForTesting
- subscribe
- TEMPLATES
- Test
- testing
- toString()
- trySet
- typeOf
- uuid
- VERSION
- ViewUtils
- warn
- wrap
Namespaces
namespace @ember/-internals/browser-environment
module '@ember/-internals/browser-environment' {}
variable hasDOM
const hasDOM: boolean;
variable history
const history: History;
variable isChrome
const isChrome: boolean;
variable isFirefox
const isFirefox: boolean;
variable location
const location: Location;
variable userAgent
const userAgent: string;
variable window
const window: Window & typeof globalThis;
namespace @ember/-internals/browser-environment/lib/has-dom
module '@ember/-internals/browser-environment/lib/has-dom' {}
variable _default
const _default: boolean;
namespace @ember/-internals/container
module '@ember/-internals/container' {}
variable INIT_FACTORY
const INIT_FACTORY: Symbol;
function getFactoryFor
getFactoryFor: ( obj: object) => InternalFactoryManager<object, FactoryClass | object> | undefined;
function privatize
privatize: ([fullName]: TemplateStringsArray) => FullName;
function setFactoryFor
setFactoryFor: <T extends object, C extends object | FactoryClass>( obj: object, factory: InternalFactoryManager<T, C>) => void;
class Container
class Container {}
A container used to instantiate and cache objects.
Every
Container
must be associated with aRegistry
, 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.Container
constructor
constructor(registry: Registry, options?: ContainerOptions);
property cache
cache: { [key: string]: object };
property factoryManagerCache
factoryManagerCache: { [key: string]: InternalFactoryManager<object, FactoryClass>;};
property isDestroyed
isDestroyed: boolean;
property isDestroying
isDestroying: boolean;
property owner
readonly owner: InternalOwner;
property registry
readonly registry: Registry & DebugRegistry;
property validationCache
readonly validationCache: { [key: string]: boolean };
method destroy
destroy: () => void;
A depth first traversal, destroying the container, its descendant containers and all their managed objects. destroy
method factoryFor
factoryFor: (fullName: FullName) => InternalFactoryManager<object> | undefined;
Given a fullName, return the corresponding factory. The consumer of the factory is responsible for the destruction of any factory instances, as there is no way for the container to ensure instances are destroyed when it itself is destroyed.
factoryFor
Parameter fullName
{any}
Modifiers
@public
method finalizeDestroy
finalizeDestroy: () => void;
method lookup
lookup: ( fullName: string, options?: RegisterOptions) => InternalFactory<object> | object | undefined;
Given a fullName return a corresponding instance. The default behavior 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 let registry = new Registry(); let container = registry.container(); registry.register('api:twitter', Twitter); let twitter = container.lookup('api:twitter'); twitter instanceof Twitter; // => true // by default the container will return singletons let 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 let registry = new Registry(); let container = registry.container(); registry.register('api:twitter', Twitter); let twitter = container.lookup('api:twitter', { singleton: false }); let twitter2 = container.lookup('api:twitter', { singleton: false }); twitter === twitter2; //=> false ``` lookup
Parameter fullName
Parameter options
{any}
method ownerInjection
ownerInjection: () => {};
Returns an object that can be used to provide an owner to a manually created instance. ownerInjection
Returns
{ Object }
method reset
reset: (fullName: FullName) => void;
Clear either the entire cache or just the cache for a particular key.
reset
Parameter fullName
optional key to reset; if missing, resets everything
class Registry
class Registry {}
A registry used to store factory and option information keyed by type.
A
Registry
stores the factory and option information needed by aContainer
to instantiate and cache objects.The API for
Registry
is still in flux and should not be considered stable.Registry 1.11.0
constructor
constructor(options?: RegistryOptions);
property fallback
readonly fallback: Registry;
property registrations
readonly registrations: Record< string, object | InternalFactory<object, FactoryClass>>;
property resolver
resolver: Resolver;
property set
set?: <T>(obj: object, keyName: string, value: T, tolerant?: boolean) => T;
method container
container: (options?: ContainerOptions) => Container;
Creates a container based on this registry.
container
Parameter options
{Container} created container
method describe
describe: (fullName: FullName) => string;
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 thefullName
.describe
Parameter fullName
{string} described fullName
method getOption
getOption: <K extends keyof RegisterOptions>( fullName: FullName, optionName: K) => RegisterOptions[K] | undefined;
method getOptions
getOptions: (fullName: FullName) => RegisterOptions | undefined;
method getOptionsForType
getOptionsForType: (type: string) => RegisterOptions | undefined;
method has
has: (fullName: FullName) => boolean;
Given a fullName check if the container is aware of its factory or singleton instance.
has
Parameter fullName
Parameter options
Parameter
{String} [options.source] the fullname of the request source (used for local lookups) {Boolean}
method isValidFullName
isValidFullName: (fullName: string) => fullName is `${string}:${string}`;
method knownForType
knownForType: <T extends string>(type: T) => KnownForTypeResult<T>;
knownForType
Parameter type
the type to iterate over
method makeToString
makeToString: (factory: InternalFactory<object>, fullName: FullName) => string;
makeToString
Parameter factory
Parameter fullName
{function} toString function
method normalize
normalize: (fullName: FullName) => FullName;
Normalize a fullName based on the application's conventions
normalize
Parameter fullName
{string} normalized fullName
method normalizeFullName
normalizeFullName: (fullName: FullName) => FullName;
A hook to enable custom fullName normalization behavior
normalizeFullName
Parameter fullName
{string} normalized fullName
method options
options: (fullName: FullName, options: RegisterOptions) => void;
options
Parameter fullName
Parameter options
method optionsForType
optionsForType: (type: string, options: RegisterOptions) => void;
Allow registering options for all factories of a type.
```javascript let registry = new Registry(); let 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);
let twitter = container.lookup('connection:twitter'); let twitter2 = container.lookup('connection:twitter');
twitter === twitter2; // => false
let facebook = container.lookup('connection:facebook'); let facebook2 = container.lookup('connection:facebook');
facebook === facebook2; // => false ```
optionsForType
Parameter type
Parameter options
method register
register: { ( fullName: FullName, factory: object, options: RegisterOptions & { instantiate: false } ): void; <T extends object, C extends object | FactoryClass>( fullName: `${string}:${string}`, factory: InternalFactory<T, C>, options?: RegisterOptions ): void;};
Registers a factory for later injection.
Example:
```javascript let registry = new Registry();
registry.register('model:user', Person, {singleton: false }); registry.register('fruit:favorite', Orange); registry.register('communication:main', Email, {singleton: false}); ```
register
Parameter fullName
Parameter factory
Parameter options
method resolve
resolve: (fullName: FullName) => InternalFactory<object> | object | undefined;
Given a fullName return the corresponding factory.
By default
resolve
will retrieve the factory from the registry.```javascript let 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 let 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 ```
resolve
Parameter fullName
{Function} fullName's factory
method unregister
unregister: (fullName: FullName) => void;
Unregister a fullName
```javascript let 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 ```
unregister
Parameter fullName
interface ResolverClass
interface ResolverClass extends Factory<Resolver>, Partial<{ new (...args: any): Resolver; }> {}
namespace @ember/-internals/container/lib/container
module '@ember/-internals/container/lib/container' {}
variable INIT_FACTORY
const INIT_FACTORY: Symbol;
function getFactoryFor
getFactoryFor: ( obj: object) => InternalFactoryManager<object, FactoryClass | object> | undefined;
function setFactoryFor
setFactoryFor: <T extends object, C extends object | FactoryClass>( obj: object, factory: InternalFactoryManager<T, C>) => void;
class Container
class Container {}
A container used to instantiate and cache objects.
Every
Container
must be associated with aRegistry
, 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.Container
constructor
constructor(registry: Registry, options?: ContainerOptions);
property cache
cache: { [key: string]: object };
property factoryManagerCache
factoryManagerCache: { [key: string]: InternalFactoryManager<object, FactoryClass>;};
property isDestroyed
isDestroyed: boolean;
property isDestroying
isDestroying: boolean;
property owner
readonly owner: InternalOwner;
property registry
readonly registry: Registry & DebugRegistry;
property validationCache
readonly validationCache: { [key: string]: boolean };
method destroy
destroy: () => void;
A depth first traversal, destroying the container, its descendant containers and all their managed objects. destroy
method factoryFor
factoryFor: (fullName: FullName) => InternalFactoryManager<object> | undefined;
Given a fullName, return the corresponding factory. The consumer of the factory is responsible for the destruction of any factory instances, as there is no way for the container to ensure instances are destroyed when it itself is destroyed.
factoryFor
Parameter fullName
{any}
Modifiers
@public
method finalizeDestroy
finalizeDestroy: () => void;
method lookup
lookup: ( fullName: string, options?: RegisterOptions) => InternalFactory<object> | object | undefined;
Given a fullName return a corresponding instance. The default behavior 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 let registry = new Registry(); let container = registry.container(); registry.register('api:twitter', Twitter); let twitter = container.lookup('api:twitter'); twitter instanceof Twitter; // => true // by default the container will return singletons let 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 let registry = new Registry(); let container = registry.container(); registry.register('api:twitter', Twitter); let twitter = container.lookup('api:twitter', { singleton: false }); let twitter2 = container.lookup('api:twitter', { singleton: false }); twitter === twitter2; //=> false ``` lookup
Parameter fullName
Parameter options
{any}
method ownerInjection
ownerInjection: () => {};
Returns an object that can be used to provide an owner to a manually created instance. ownerInjection
Returns
{ Object }
method reset
reset: (fullName: FullName) => void;
Clear either the entire cache or just the cache for a particular key.
reset
Parameter fullName
optional key to reset; if missing, resets everything
class InternalFactoryManager
class InternalFactoryManager< T extends object, C extends FactoryClass | object = FactoryClass> implements FactoryManager<T> {}
constructor
constructor( container: Container, factory: InternalFactory<T, C>, fullName: string, normalizedName: string);
property class
readonly class: DebugFactory<T, C>;
property container
readonly container: Container;
property fullName
readonly fullName: string;
property injections
injections: { [key: string]: unknown };
property normalizedName
readonly normalizedName: string;
property owner
readonly owner: InternalOwner;
method create
create: (options?: Partial<T>) => T;
method toString
toString: () => string;
interface ContainerOptions
interface ContainerOptions {}
property cache
cache?: { [key: string]: object;};
property factoryManagerCache
factoryManagerCache?: { [key: string]: InternalFactoryManager<any, any>;};
property owner
owner?: InternalOwner;
property validationCache
validationCache?: { [key: string]: boolean;};
interface LazyInjection
interface LazyInjection {}
namespace @ember/-internals/container/lib/registry
module '@ember/-internals/container/lib/registry' {}
function privatize
privatize: ([fullName]: TemplateStringsArray) => FullName;
class DebugRegistry
class DebugRegistry extends Registry {}
method normalizeInjectionsHash
normalizeInjectionsHash: (hash: { [key: string]: LazyInjection }) => Injection[];
method validateInjections
validateInjections: (injections: Injection[]) => void;
class Registry
class Registry {}
A registry used to store factory and option information keyed by type.
A
Registry
stores the factory and option information needed by aContainer
to instantiate and cache objects.The API for
Registry
is still in flux and should not be considered stable.Registry 1.11.0
constructor
constructor(options?: RegistryOptions);
property fallback
readonly fallback: Registry;
property registrations
readonly registrations: Record< string, object | InternalFactory<object, FactoryClass>>;
property resolver
resolver: Resolver;
property set
set?: <T>(obj: object, keyName: string, value: T, tolerant?: boolean) => T;
method container
container: (options?: ContainerOptions) => Container;
Creates a container based on this registry.
container
Parameter options
{Container} created container
method describe
describe: (fullName: FullName) => string;
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 thefullName
.describe
Parameter fullName
{string} described fullName
method getOption
getOption: <K extends keyof RegisterOptions>( fullName: FullName, optionName: K) => RegisterOptions[K] | undefined;
method getOptions
getOptions: (fullName: FullName) => RegisterOptions | undefined;
method getOptionsForType
getOptionsForType: (type: string) => RegisterOptions | undefined;
method has
has: (fullName: FullName) => boolean;
Given a fullName check if the container is aware of its factory or singleton instance.
has
Parameter fullName
Parameter options
Parameter
{String} [options.source] the fullname of the request source (used for local lookups) {Boolean}
method isValidFullName
isValidFullName: (fullName: string) => fullName is `${string}:${string}`;
method knownForType
knownForType: <T extends string>(type: T) => KnownForTypeResult<T>;
knownForType
Parameter type
the type to iterate over
method makeToString
makeToString: (factory: InternalFactory<object>, fullName: FullName) => string;
makeToString
Parameter factory
Parameter fullName
{function} toString function
method normalize
normalize: (fullName: FullName) => FullName;
Normalize a fullName based on the application's conventions
normalize
Parameter fullName
{string} normalized fullName
method normalizeFullName
normalizeFullName: (fullName: FullName) => FullName;
A hook to enable custom fullName normalization behavior
normalizeFullName
Parameter fullName
{string} normalized fullName
method options
options: (fullName: FullName, options: RegisterOptions) => void;
options
Parameter fullName
Parameter options
method optionsForType
optionsForType: (type: string, options: RegisterOptions) => void;
Allow registering options for all factories of a type.
```javascript let registry = new Registry(); let 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);
let twitter = container.lookup('connection:twitter'); let twitter2 = container.lookup('connection:twitter');
twitter === twitter2; // => false
let facebook = container.lookup('connection:facebook'); let facebook2 = container.lookup('connection:facebook');
facebook === facebook2; // => false ```
optionsForType
Parameter type
Parameter options
method register
register: { ( fullName: FullName, factory: object, options: RegisterOptions & { instantiate: false } ): void; <T extends object, C extends object | FactoryClass>( fullName: `${string}:${string}`, factory: InternalFactory<T, C>, options?: RegisterOptions ): void;};
Registers a factory for later injection.
Example:
```javascript let registry = new Registry();
registry.register('model:user', Person, {singleton: false }); registry.register('fruit:favorite', Orange); registry.register('communication:main', Email, {singleton: false}); ```
register
Parameter fullName
Parameter factory
Parameter options
method resolve
resolve: (fullName: FullName) => InternalFactory<object> | object | undefined;
Given a fullName return the corresponding factory.
By default
resolve
will retrieve the factory from the registry.```javascript let 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 let 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 ```
resolve
Parameter fullName
{Function} fullName's factory
method unregister
unregister: (fullName: FullName) => void;
Unregister a fullName
```javascript let 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 ```
unregister
Parameter fullName
interface Injection
interface Injection {}
interface RegistryOptions
interface RegistryOptions {}
property fallback
fallback?: Registry;
property registrations
registrations?: { [key: string]: object;};
property resolver
resolver?: Resolver;
interface ResolverClass
interface ResolverClass extends Factory<Resolver>, Partial<{ new (...args: any): Resolver; }> {}
namespace @ember/-internals/deprecations
module '@ember/-internals/deprecations' {}
variable DEPRECATIONS
const DEPRECATIONS: { DEPRECATE_IMPORT_EMBER(importName: string): { options: DeprecationOptions; test: boolean; isEnabled: boolean; isRemoved: boolean; }; DEPRECATE_IMPLICIT_ROUTE_MODEL: { options: DeprecationOptions; test: boolean; isEnabled: boolean; isRemoved: boolean; }; DEPRECATE_TEMPLATE_ACTION: { options: DeprecationOptions; test: boolean; isEnabled: boolean; isRemoved: boolean; }; DEPRECATE_COMPONENT_TEMPLATE_RESOLVING: { options: DeprecationOptions; test: boolean; isEnabled: boolean; isRemoved: boolean; }; DEPRECATE_ARRAY_PROTOTYPE_EXTENSIONS: { options: DeprecationOptions; test: boolean; isEnabled: boolean; isRemoved: boolean; };};
function deprecateUntil
deprecateUntil: (message: string, deprecation: DeprecationObject) => void;
function emberVersionGte
emberVersionGte: (until: string, emberVersion?: number) => boolean;
function isRemoved
isRemoved: (options: DeprecationOptions) => boolean;
namespace @ember/-internals/environment
module '@ember/-internals/environment' {}
variable context
const context: GlobalContext;
variable ENV
const ENV: { ENABLE_OPTIONAL_FEATURES: boolean; EXTEND_PROTOTYPES: { Array: boolean }; LOG_STACKTRACE_ON_DEPRECATION: boolean; LOG_VERSION: boolean; RAISE_ON_DEPRECATION: boolean; STRUCTURED_PROFILE: boolean; _DEBUG_RENDER_TREE: boolean; _ALL_DEPRECATIONS_ENABLED: boolean; _OVERRIDE_DEPRECATION_VERSION: null; _DEFAULT_ASYNC_OBSERVERS: boolean; _NO_IMPLICIT_ROUTE_MODEL: boolean; _RERENDER_LOOP_LIMIT: number; EMBER_LOAD_HOOKS: { [hook: string]: Function[] }; FEATURES: { [feature: string]: boolean };};
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
(orENV
for backwards compatibility with earlier versions of Ember). TheEmberENV
hash must be created before loading Ember.EmberENV Object
Modifiers
@public
variable global
const global: any;
function getENV
getENV: () => object;
function getLookup
getLookup: () => Record<string, unknown>;
function setLookup
setLookup: (value: Record<string, unknown>) => void;
interface GlobalContext
interface GlobalContext {}
namespace @ember/-internals/environment/lib/context
module '@ember/-internals/environment/lib/context' {}
variable context
const context: GlobalContext;
function getLookup
getLookup: () => Record<string, unknown>;
function setLookup
setLookup: (value: Record<string, unknown>) => void;
interface GlobalContext
interface GlobalContext {}
namespace @ember/-internals/environment/lib/env
module '@ember/-internals/environment/lib/env' {}
variable ENV
const ENV: { ENABLE_OPTIONAL_FEATURES: boolean; EXTEND_PROTOTYPES: { Array: boolean }; LOG_STACKTRACE_ON_DEPRECATION: boolean; LOG_VERSION: boolean; RAISE_ON_DEPRECATION: boolean; STRUCTURED_PROFILE: boolean; _DEBUG_RENDER_TREE: boolean; _ALL_DEPRECATIONS_ENABLED: boolean; _OVERRIDE_DEPRECATION_VERSION: null; _DEFAULT_ASYNC_OBSERVERS: boolean; _NO_IMPLICIT_ROUTE_MODEL: boolean; _RERENDER_LOOP_LIMIT: number; EMBER_LOAD_HOOKS: { [hook: string]: Function[] }; FEATURES: { [feature: string]: boolean };};
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
(orENV
for backwards compatibility with earlier versions of Ember). TheEmberENV
hash must be created before loading Ember.EmberENV Object
Modifiers
@public
function getENV
getENV: () => object;
namespace @ember/-internals/environment/lib/global
module '@ember/-internals/environment/lib/global' {}
variable _default
const _default: any;
namespace @ember/-internals/error-handling
module '@ember/-internals/error-handling' {}
variable onErrorTarget
const onErrorTarget: { readonly onerror: Function | undefined };
function getDispatchOverride
getDispatchOverride: () => Function | null;
function getOnerror
getOnerror: () => Function | undefined;
function setDispatchOverride
setDispatchOverride: (handler: Function | null) => void;
function setOnerror
setOnerror: (handler: Function | undefined) => void;
namespace @ember/-internals/glimmer
module '@ember/-internals/glimmer' {}
variable Input
const Input: Input;
variable LinkTo
const LinkTo: LinkTo;
variable RootTemplate
const RootTemplate: any;
variable Textarea
const Textarea: Textarea;
function escapeExpression
escapeExpression: (string: unknown) => string;
function getTemplate
getTemplate: (name: string) => TemplateFactory | void;
function getTemplates
getTemplates: () => TemplatesRegistry;
function hasTemplate
hasTemplate: (name: string) => boolean;
function helper
helper: { <P extends DefaultPositional, N extends object, R = unknown>( helperFn: (positional: P, named: N) => R ): FunctionBasedHelper<{ Args: { Positional: P; Named: N }; Return: R }>; <S>( helperFn: ( positional: GetOr<GetOr<S, 'Args', {}>, 'Positional', DefaultPositional>, named: GetOr<GetOr<S, 'Args', {}>, 'Named', object> ) => GetOr<S, 'Return', unknown> ): FunctionBasedHelper<S>;};
In many cases it is not necessary to use the full
Helper
class. Thehelper
method create pure-function helpers without instances. For example:```app/helpers/format-currency.js import { helper } from '@ember/component/helper';
export default helper(function([cents], {currency}) { return
${currency}${cents * 0.01}
; }); ```Parameter helper
The helper function helper @ember/component/helper
1.13.0
Modifiers
@public
function htmlSafe
htmlSafe: (str: string) => SafeString;
Use this method to indicate that a string should be rendered as HTML when the string is used in a template. To say this another way, strings marked with
htmlSafe
will not be HTML escaped.A word of warning - The
htmlSafe
method does not make the string safe; it only tells the framework to treat the string as if it is safe to render as HTML. If a string contains user inputs or other untrusted data, you must sanitize the string before using thehtmlSafe
method. Otherwise your code is vulnerable to [Cross-Site Scripting](https://owasp.org/www-community/attacks/DOM_Based_XSS). There are many open source sanitization libraries to choose from, both for front end and server-side sanitization.```javascript import { htmlSafe } from '@ember/template';
const someTrustedOrSanitizedString = "Hello!"
htmlSafe(someTrustedorSanitizedString) ```
htmlSafe @ember/template
Parameter str
The string to treat as trusted. {SafeString} A string that will not be HTML escaped by Handlebars.
Modifiers
@public
function isHTMLSafe
isHTMLSafe: (str: unknown) => str is SafeString;
Detects if a string was decorated using
htmlSafe
.```javascript import { htmlSafe, isHTMLSafe } from '@ember/template';
let plainString = 'plain string'; let safeString = htmlSafe('someValue');
isHTMLSafe(plainString); // false isHTMLSafe(safeString); // true ```
isHTMLSafe @ember/template {Boolean}
true
if the string was decorated withhtmlSafe
,false
otherwise.Modifiers
@public
function renderSettled
renderSettled: () => RSVP.Promise<void>;
function setComponentManager
setComponentManager: <T extends object>( manager: (owner: InternalOwner) => ComponentManager<unknown>, obj: T) => T;
Associate a class with a component manager (an object that is responsible for coordinating the lifecycle events that occurs when invoking, rendering and re-rendering a component).
setComponentManager
Parameter factory
a function to create the owner for an object
Parameter obj
the object to associate with the componetn manager {Object} the same object passed in
Modifiers
@public
function setTemplate
setTemplate: (name: string, template: TemplateFactory) => TemplateFactory;
function setTemplates
setTemplates: (templates: TemplatesRegistry) => void;
function setupApplicationRegistry
setupApplicationRegistry: (registry: Registry) => void;
function setupEngineRegistry
setupEngineRegistry: (registry: Registry) => void;
function uniqueId
uniqueId: () => string;
class Component
class Component<S = unknown> extends Component_base implements PropertyDidChange {}
property [DIRTY_TAG]
[DIRTY_TAG]: DirtyableTag;
property [IS_DISPATCHING_ATTRS]
[IS_DISPATCHING_ATTRS]: boolean;
property ariaRole
ariaRole?: string;
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: [https://www.w3.org/TR/wai-aria/#roles_categorization](https://www.w3.org/TR/wai-aria/#roles_categorization)
ariaRole String undefined
Modifiers
@public
property attributeBindings
attributeBindings?: string[];
property isComponent
isComponent: boolean;
property isComponentFactory
static isComponentFactory: boolean;
property layout
layout?: any;
Layout can be used to wrap content in a component. layout Function
Modifiers
@public
property layoutName
layoutName?: string;
The name of the layout to lookup if no layout is provided. By default
Component
will lookup a template with this name inEmber.TEMPLATES
(a shared global object). layoutName String undefined
property positionalParams
static positionalParams: string | string[];
Enables components to take a list of parameters as arguments. For example, a component that takes two parameters with the names
name
andage
:```app/components/my-component.js import Component from '@ember/component';
let MyComponent = Component.extend();
MyComponent.reopenClass({ positionalParams: ['name', 'age'] });
export default MyComponent; ```
It can then be invoked like this:
```hbs {{my-component "John" 38}} ```
The parameters can be referred to just like named parameters:
```hbs Name: {{name}}, Age: {{age}}. ```
Using a string instead of an array allows for an arbitrary number of parameters:
```app/components/my-component.js import Component from '@ember/component';
let MyComponent = Component.extend();
MyComponent.reopenClass({ positionalParams: 'names' });
export default MyComponent; ```
It can then be invoked like this:
```hbs {{my-component "John" "Michael" "Scott"}} ``` The parameters can then be referred to by enumerating over the list:
```hbs {{#each names as |name|}}{{name}}{{/each}} ```
positionalParams 1.13.0
Modifiers
@public
method [PROPERTY_DID_CHANGE]
[PROPERTY_DID_CHANGE]: (key: string, value?: unknown) => void;
method getAttr
getAttr: (key: string) => unknown;
method init
init: (properties?: object | undefined) => void;
method on
on: { <Target>( name: string, target: Target, method: string | ((this: Target, ...args: any[]) => void) ): this; (name: string, method: string | ((...args: any[]) => void)): this;};
method readDOMAttr
readDOMAttr: (name: string) => any;
Normally, Ember's component model is "write-only". The component takes a bunch of attributes that it got passed in, and uses them to render its template.
One nice thing about this model is that if you try to set a value to the same thing as last time, Ember (through HTMLBars) will avoid doing any work on the DOM.
This is not just a performance optimization. If an attribute has not changed, it is important not to clobber the element's "hidden state". For example, if you set an input's
value
to the same value as before, it will clobber selection state and cursor position. In other words, setting an attribute is not **always** idempotent.This method provides a way to read an element's attribute and also update the last value Ember knows about at the same time. This makes setting an attribute idempotent.
In particular, what this means is that if you get an
<input>
element'svalue
attribute and then re-render the template with the same value, it will avoid clobbering the cursor and selection position. Since most attribute sets are idempotent in the browser, you typically can get away with reading attributes using jQuery, but the most reliable way to do so is through this method. readDOMAttrParameter name
the name of the attribute String
Modifiers
@public
method toString
static toString: () => string;
class FunctionBasedHelperInstance
abstract class FunctionBasedHelperInstance<S> extends Helper<S> {}
class Helper
class Helper<S = unknown> extends FrameworkObject {}
property [IS_CLASSIC_HELPER]
static [IS_CLASSIC_HELPER]: boolean;
property [RECOMPUTE_TAG]
[RECOMPUTE_TAG]: DirtyableTag;
property helper
static helper: { <P extends DefaultPositional, N extends object, R = unknown>( helperFn: (positional: P, named: N) => R ): FunctionBasedHelper<{ Args: { Positional: P; Named: N }; Return: R }>; <S>( helperFn: ( positional: GetOr< GetOr<S, 'Args', {}>, 'Positional', DefaultPositional >, named: GetOr<GetOr<S, 'Args', {}>, 'Named', object> ) => GetOr<S, 'Return', unknown> ): FunctionBasedHelper<S>;};
Deprecated
property isHelperFactory
static isHelperFactory: boolean;
method init
init: (properties: object | undefined) => void;
method recompute
recompute: () => void;
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:```app/helpers/current-user-email.js import Helper from '@ember/component/helper' import { service } from '@ember/service' import { observer } from '@ember/object'
export default Helper.extend({ session: service(),
onNewUser: observer('session.currentUser', function() { this.recompute(); }),
compute() { return this.get('session.currentUser.email'); } }); ```
recompute
1.13.0
Modifiers
@public
class OutletView
class OutletView {}
constructor
constructor( _environment: BootEnvironment, owner: InternalOwner, template: Template, namespace: any);
property namespace
namespace: any;
property owner
owner: InternalOwner;
property state
state: OutletDefinitionState;
property template
template: Template;
method appendTo
appendTo: (selector: string | SimpleElement) => void;
method create
static create: (options: { environment: BootEnvironment; application: InternalOwner; template: TemplateFactory;}) => OutletView;
method destroy
destroy: () => void;
method extend
static extend: (injections: any) => typeof OutletView;
method reopenClass
static reopenClass: (injections: any) => void;
method rerender
rerender: () => void;
method setOutletState
setOutletState: (state: OutletState) => void;
class Renderer
class Renderer {}
constructor
constructor( owner: InternalOwner, document: SimpleDocument, env: { isInteractive: boolean; hasDOM: boolean }, rootTemplate: TemplateFactory, viewRegistry: ViewRegistry, builder?: any);
property debugRenderTree
readonly debugRenderTree: DebugRenderTree;
method appendOutletView
appendOutletView: (view: OutletView, target: SimpleElement) => void;
method appendTo
appendTo: (view: Component, target: SimpleElement) => void;
method cleanupRootFor
cleanupRootFor: (view: unknown) => void;
method create
static create: (props: { _viewRegistry: any }) => Renderer;
method createElement
createElement: (tagName: string) => SimpleElement;
method destroy
destroy: () => void;
method getBounds
getBounds: (view: View) => { parentElement: SimpleElement; firstNode: SimpleNode; lastNode: SimpleNode;};
method getElement
getElement: (view: View) => Nullable<Element>;
method register
register: (view: any) => void;
method remove
remove: (view: Component) => void;
method rerender
rerender: () => void;
method unregister
unregister: (view: any) => void;
class SafeString
class SafeString implements GlimmerSafeString {}
A wrapper around a string that has been marked as safe ("trusted"). **When rendered in HTML, Ember will not perform any escaping.**
Note:
1. This does not *make* the string safe; it means that some code in your application has *marked* it as safe using the
htmlSafe()
function.2. The only public API for getting a
SafeString
is callinghtmlSafe()
. It is *not* user-constructible.If a string contains user inputs or other untrusted data, you must sanitize the string before using the
htmlSafe
method. Otherwise your code is vulnerable to [Cross-Site Scripting][xss]. There are many open source sanitization libraries to choose from, both for front end and server-side sanitization.[xss]: https://owasp.org/www-community/attacks/DOM_Based_XSS
```javascript import { htmlSafe } from '@ember/template';
let someTrustedOrSanitizedString = "Hello!"
htmlSafe(someTrustedorSanitizedString); ```
@ember/template SafeString 4.12.0
Modifiers
@public
constructor
constructor(string: string);
method toHTML
toHTML: () => string;
Get the wrapped string as HTML to use without escaping.
toHTML
Returns
{String} the trusted string, without any escaping applied
Modifiers
@public
method toString
toString: () => string;
Get the string back to use as a string.
toString
Returns
{String} The string marked as trusted
Modifiers
@public
interface BootEnvironment
interface BootEnvironment {}
property hasDOM
hasDOM: boolean;
property isInteractive
isInteractive: boolean;
property options
options: BootOptions;
interface Component
interface Component<S = unknown> extends CoreView, ChildViewsSupport, ViewStateSupport, ClassNamesSupport, TargetActionSupport, ActionSupport, ViewMixin, ComponentMethods {}
A component is a reusable UI element that consists of a
.hbs
template and an optional JavaScript class that defines its behavior. For example, someone might make abutton
in the template and handle the click behavior in the JavaScript file that shares the same name as the template.Components are broken down into two categories:
- Components _without_ JavaScript, that are based only on a template. These are called Template-only or TO components. - Components _with_ JavaScript, which consist of a template and a backing class.
Ember ships with two types of JavaScript classes for components:
1. Glimmer components, imported from
@glimmer/component
, which are the default component's for Ember Octane (3.15) and more recent editions. 2. Classic components, imported from@ember/component
, which were the default for older editions of Ember (pre 3.15).Below is the documentation for Classic components. If you are looking for the API documentation for Template-only or Glimmer components, it is [available here](/ember/release/modules/@glimmer%2Fcomponent).
## Defining a Classic Component
If you want to customize the component in order to handle events, transform arguments or maintain internal state, you implement a subclass of
Component
.One example is to add computed properties to your component:
```app/components/person-profile.js import Component from '@ember/component';
export default Component.extend({ displayName: computed('person.title', 'person.firstName', 'person.lastName', function() { let { title, firstName, lastName } = this.person;
if (title) { return
${title} ${lastName}
; } else { return${firstName} ${lastName}
; } }) }); ```And then use it in the component's template:
```app/templates/components/person-profile.hbs {{this.displayName}} {{yield}} ```
## Customizing a Classic Component's HTML Element in JavaScript
### HTML Tag
The default HTML tag name used for a component's HTML representation is
div
. This can be customized by setting thetagName
property.Consider the following component class:
```app/components/emphasized-paragraph.js import Component from '@ember/component';
export default Component.extend({ tagName: 'em' }); ```
When invoked, this component would produce output that looks something like this:
```html ```
### HTML
class
AttributeThe HTML
class
attribute of a component's tag can be set by providing aclassNames
property that is set to an array of strings:```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ classNames: ['my-class', 'my-other-class'] }); ```
Invoking this component will produce output that looks like this:
```html ```
class
attribute values can also be set by providing aclassNameBindings
property set to an array of properties names for the component. The return value of these properties will be added as part of the value for the components'sclass
attribute. These properties can be computed properties:```app/components/my-widget.js import Component from '@ember/component'; import { computed } from '@ember/object';
export default Component.extend({ classNames: ['my-class', 'my-other-class'], classNameBindings: ['propertyA', 'propertyB'],
propertyA: 'from-a', propertyB: computed(function() { if (someLogic) { return 'from-b'; } }) }); ```
Invoking this component will produce HTML that looks like:
```html ```
Note that
classNames
andclassNameBindings
is in addition to theclass
attribute passed with the angle bracket invocation syntax. Therefore, if this component was invoked like so:```handlebars ```
The resulting HTML will look similar to this:
```html ```
If the value of a class name binding returns a boolean the property name itself will be used as the class name if the property is true. The class name will not be added if the value is
false
orundefined
.```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ classNameBindings: ['hovered'],
hovered: true }); ```
Invoking this component will produce HTML that looks like:
```html ```
### Custom Class Names for Boolean Values
When using boolean class name bindings you can supply a string value other than the property name for use as the
class
HTML attribute by appending the preferred value after a ":" character when defining the binding:```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ classNameBindings: ['awesome:so-very-cool'],
awesome: true }); ```
Invoking this component will produce HTML that looks like:
```html ```
Boolean value class name bindings whose property names are in a camelCase-style format will be converted to a dasherized format:
```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ classNameBindings: ['isUrgent'],
isUrgent: true }); ```
Invoking this component will produce HTML that looks like:
```html ```
Class name bindings can also refer to object values that are found by traversing a path relative to the component itself:
```app/components/my-widget.js import Component from '@ember/component'; import EmberObject from '@ember/object';
export default Component.extend({ classNameBindings: ['messages.empty'],
messages: EmberObject.create({ empty: true }) }); ```
Invoking this component will produce HTML that looks like:
```html ```
If you want to add a class name for a property which evaluates to true and and a different class name if it evaluates to false, you can pass a binding like this:
```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ classNameBindings: ['isEnabled:enabled:disabled'], isEnabled: true }); ```
Invoking this component will produce HTML that looks like:
```html ```
When isEnabled is
false
, the resulting HTML representation looks like this:```html ```
This syntax offers the convenience to add a class if a property is
false
:```app/components/my-widget.js import Component from '@ember/component';
// Applies no class when isEnabled is true and class 'disabled' when isEnabled is false export default Component.extend({ classNameBindings: ['isEnabled::disabled'], isEnabled: true }); ```
Invoking this component when the
isEnabled
property is true will produce HTML that looks like:```html ```
Invoking it when the
isEnabled
property on the component isfalse
will produce HTML that looks like:```html ```
Updates to the value of a class name binding will result in automatic update of the HTML
class
attribute in the component's rendered HTML representation. If the value becomesfalse
orundefined
the class name will be removed.Both
classNames
andclassNameBindings
are concatenated properties. See [EmberObject](/ember/release/classes/EmberObject) documentation for more information about concatenated properties.### Other HTML Attributes
The HTML attribute section of a component's tag can be set by providing an
attributeBindings
property set to an array of property names on the component. The return value of these properties will be used as the value of the component's HTML associated attribute:```app/components/my-anchor.js import Component from '@ember/component';
export default Component.extend({ tagName: 'a', attributeBindings: ['href'],
href: 'http://google.com' }); ```
Invoking this component will produce HTML that looks like:
```html ```
One property can be mapped on to another by placing a ":" between the source property and the destination property:
```app/components/my-anchor.js import Component from '@ember/component';
export default Component.extend({ tagName: 'a', attributeBindings: ['url:href'],
url: 'http://google.com' }); ```
Invoking this component will produce HTML that looks like:
```html ```
HTML attributes passed with angle bracket invocations will take precedence over those specified in
attributeBindings
. Therefore, if this component was invoked like so:```handlebars <MyAnchor href="http://bing.com" @url="http://google.com" /> ```
The resulting HTML will looks like this:
```html ```
Note that the
href
attribute is ultimately set tohttp://bing.com
, despite it having attribute binidng to theurl
property, which was set tohttp://google.com
.Namespaced attributes (e.g.
xlink:href
) are supported, but have to be mapped, since:
is not a valid character for properties in Javascript:```app/components/my-use.js import Component from '@ember/component';
export default Component.extend({ tagName: 'use', attributeBindings: ['xlinkHref:xlink:href'],
xlinkHref: '#triangle' }); ```
Invoking this component will produce HTML that looks like:
```html <use xlink:href="#triangle"> ```
If the value of a property monitored by
attributeBindings
is a boolean, the attribute will be present or absent depending on the value:```app/components/my-text-input.js import Component from '@ember/component';
export default Component.extend({ tagName: 'input', attributeBindings: ['disabled'],
disabled: false }); ```
Invoking this component will produce HTML that looks like:
```html ```
attributeBindings
can refer to computed properties:```app/components/my-text-input.js import Component from '@ember/component'; import { computed } from '@ember/object';
export default Component.extend({ tagName: 'input', attributeBindings: ['disabled'],
disabled: computed(function() { if (someLogic) { return true; } else { return false; } }) }); ```
To prevent setting an attribute altogether, use
null
orundefined
as the value of the property used inattributeBindings
:```app/components/my-text-input.js import Component from '@ember/component';
export default Component.extend({ tagName: 'form', attributeBindings: ['novalidate'], novalidate: null }); ```
Updates to the property of an attribute binding will result in automatic update of the HTML attribute in the component's HTML output.
attributeBindings
is a concatenated property. See [EmberObject](/ember/release/classes/EmberObject) documentation for more information about concatenated properties.## Layouts
The
layout
property can be used to dynamically specify a template associated with a component class, instead of relying on Ember to link together a component class and a template based on file names.In general, applications should not use this feature, but it's commonly used in addons for historical reasons.
The
layout
property should be set to the default export of a template module, which is the name of a template file without the.hbs
extension.```app/templates/components/person-profile.hbs Person's Title {{yield}} ```
```app/components/person-profile.js import Component from '@ember/component'; import layout from '../templates/components/person-profile';
export default Component.extend({ layout }); ```
If you invoke the component:
```handlebars Chief Basket Weaver Fisherman Industries ```
or
```handlebars {{#person-profile}} Chief Basket Weaver Fisherman Industries {{/person-profile}} ```
It will result in the following HTML output:
```html Person's Title Chief Basket Weaver Fisherman Industries ```
## Handling Browser Events
There are two ways to handle user-initiated events:
### Using the
on
modifier to capture browser eventsIn a component's template, you can attach an event handler to any element with the
on
modifier:```handlebars <button {{on 'click' this.doSomething}} /> ```
This will call the function on your component:
```js import Component from '@ember/component';
export default class ExampleComponent extends Component { doSomething = (event) => { //
event
is the native click Event console.log('clicked on the button'); }; }); ```See the [Guide on Component event handlers](https://guides.emberjs.com/release/components/component-state-and-actions/#toc_html-modifiers-and-actions) and the [API docs for
on
](../Ember.Templates.helpers/methods/on?anchor=on) for more details.### Event Handler Methods
Components can also respond to user-initiated events by implementing a method that matches the event name. This approach is appropriate when the same event should be handled by all instances of the same component.
An event object will be passed as the argument to the event handler method.
```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ click(event) { //
event.target
is either the component's element or one of its children let tag = event.target.tagName.toLowerCase(); console.log('clicked on a<${tag}>
HTML element!'); } }); ```In this example, whenever the user clicked anywhere inside the component, it will log a message to the console.
It is possible to handle event types other than
click
by implementing the following event handler methods. In addition, custom events can be registered by usingApplication.customEvents
.Touch events:
touchStart
touchMove
touchEnd
touchCancel
Keyboard events:
keyDown
keyUp
keyPress
Mouse events:
mouseDown
mouseUp
contextMenu
click
doubleClick
focusIn
focusOut
Form events:
submit
change
focusIn
focusOut
input
Drag and drop events:
dragStart
drag
dragEnter
dragLeave
dragOver
dragEnd
drop
Component Ember.CoreView Ember.TargetActionSupport Ember.ClassNamesSupport Ember.ActionSupport Ember.ViewMixin Ember.ViewStateSupport
Modifiers
@public
interface Helper
interface Helper<S = unknown> {}
Ember Helpers are functions that can compute values, and are used in templates. For example, this code calls a helper named
format-currency
:```app/templates/application.hbs <Cost @cents={{230}} /> ```
```app/components/cost.hbs {{format-currency currency="$"}} ```
Additionally a helper can be called as a nested helper. In this example, we show the formatted currency value if the
showMoney
named argument is truthy.```handlebars {{if (format-currency currency="$")}} ```
Helpers defined using a class must provide a
compute
function. For example:```app/helpers/format-currency.js import Helper from '@ember/component/helper';
export default class extends Helper { compute([cents], { 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 and will accept injected dependencies.
Additionally, class helpers can call
recompute
to force a new computation.Helper CoreObject
1.13.0
Modifiers
@public
method compute
compute: (positional: Positional<S>, named: Named<S>) => Return<S>;
Override this function when writing a class-based helper.
compute
Parameter positional
The positional arguments to the helper
Parameter named
The named arguments to the helper
1.13.0
Modifiers
@public
interface Input
interface Input extends Opaque<'component:input'>, OpaqueInternalComponentConstructor {}
interface LinkTo
interface LinkTo extends Opaque<'component:link-to'>, OpaqueInternalComponentConstructor {}
interface OutletState
interface OutletState {}
property outlets
outlets: { main: OutletState | undefined;};
Represents what, if any, should be rendered into the next {{outlet}} found at this level.
This used to be a dictionary of children outlets, including the {{outlet}} "main" outlet any {{outlet "named"}} named outlets. Since named outlets are not a thing anymore, this can now just be a single
child
.
property render
render: RenderState | undefined;
Represents what was rendered into this outlet.
property wasUsed
wasUsed?: undefined;
Deprecated
This tracks whether this outlet state actually made it onto the page somewhere. This was more of a problem when you can declare named outlets left and right, and anything can render into anywhere else. We want to warn users when you tried to render into somewhere that does not exist, but we don't know what named outlets exists until after we have rendered everything, so this was used to track these orphan renders.
This can still happen, if, according to the router, a route is active and so its template should be rendered, but the parent template is missing the
{{outlet}}
keyword, or that it was hidden by an{{#if}}
or something. I guess that is considered valid, because nothing checks for this anymore. seems valid for the parent to decide not to render a child template?
interface RenderState
interface RenderState {}
property controller
controller: unknown;
The controller (the self of the outlet component)
property into
into: undefined;
Deprecated
This used to specify "which parent route to render into", which is not a thing anymore.
property model
model: unknown;
The model (the resolved value of the model hook)
property name
name: string;
The name of the route/template
property outlet
outlet: 'main';
Deprecated
This used to specify "which named outlet in the parent template to render into", which is not a thing anymore.
property owner
owner: InternalOwner;
This is usually inherited from the parent (all the way up to the app instance). However, engines uses this to swap out the owner when crossing a mount point.
property template
template: Template | undefined;
template (the layout of the outlet component)
interface TemplatesRegistry
interface TemplatesRegistry {}
index signature
[name: string]: TemplateFactory;
interface Textarea
interface Textarea extends Opaque<'component:textarea'>, OpaqueInternalComponentConstructor {}
type FunctionBasedHelper
type FunctionBasedHelper<S> = abstract new () => FunctionBasedHelperInstance<S>;
The type of a function-based helper.
This is *not* user-constructible: it is exported only so that the type returned by the
helper
function can be named (and indeed can be exported likeexport default helper(...)
safely).
namespace @ember/-internals/glimmer/lib/component
module '@ember/-internals/glimmer/lib/component' {}
class Component
class Component<S = unknown> extends Component_base implements PropertyDidChange {}
property [DIRTY_TAG]
[DIRTY_TAG]: DirtyableTag;
property [IS_DISPATCHING_ATTRS]
[IS_DISPATCHING_ATTRS]: boolean;
property ariaRole
ariaRole?: string;
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: [https://www.w3.org/TR/wai-aria/#roles_categorization](https://www.w3.org/TR/wai-aria/#roles_categorization)
ariaRole String undefined
Modifiers
@public
property attributeBindings
attributeBindings?: string[];
property isComponent
isComponent: boolean;
property isComponentFactory
static isComponentFactory: boolean;
property layout
layout?: any;
Layout can be used to wrap content in a component. layout Function
Modifiers
@public
property layoutName
layoutName?: string;
The name of the layout to lookup if no layout is provided. By default
Component
will lookup a template with this name inEmber.TEMPLATES
(a shared global object). layoutName String undefined
property positionalParams
static positionalParams: string | string[];
Enables components to take a list of parameters as arguments. For example, a component that takes two parameters with the names
name
andage
:```app/components/my-component.js import Component from '@ember/component';
let MyComponent = Component.extend();
MyComponent.reopenClass({ positionalParams: ['name', 'age'] });
export default MyComponent; ```
It can then be invoked like this:
```hbs {{my-component "John" 38}} ```
The parameters can be referred to just like named parameters:
```hbs Name: {{name}}, Age: {{age}}. ```
Using a string instead of an array allows for an arbitrary number of parameters:
```app/components/my-component.js import Component from '@ember/component';
let MyComponent = Component.extend();
MyComponent.reopenClass({ positionalParams: 'names' });
export default MyComponent; ```
It can then be invoked like this:
```hbs {{my-component "John" "Michael" "Scott"}} ``` The parameters can then be referred to by enumerating over the list:
```hbs {{#each names as |name|}}{{name}}{{/each}} ```
positionalParams 1.13.0
Modifiers
@public
method [PROPERTY_DID_CHANGE]
[PROPERTY_DID_CHANGE]: (key: string, value?: unknown) => void;
method getAttr
getAttr: (key: string) => unknown;
method init
init: (properties?: object | undefined) => void;
method on
on: { <Target>( name: string, target: Target, method: string | ((this: Target, ...args: any[]) => void) ): this; (name: string, method: string | ((...args: any[]) => void)): this;};
method readDOMAttr
readDOMAttr: (name: string) => any;
Normally, Ember's component model is "write-only". The component takes a bunch of attributes that it got passed in, and uses them to render its template.
One nice thing about this model is that if you try to set a value to the same thing as last time, Ember (through HTMLBars) will avoid doing any work on the DOM.
This is not just a performance optimization. If an attribute has not changed, it is important not to clobber the element's "hidden state". For example, if you set an input's
value
to the same value as before, it will clobber selection state and cursor position. In other words, setting an attribute is not **always** idempotent.This method provides a way to read an element's attribute and also update the last value Ember knows about at the same time. This makes setting an attribute idempotent.
In particular, what this means is that if you get an
<input>
element'svalue
attribute and then re-render the template with the same value, it will avoid clobbering the cursor and selection position. Since most attribute sets are idempotent in the browser, you typically can get away with reading attributes using jQuery, but the most reliable way to do so is through this method. readDOMAttrParameter name
the name of the attribute String
Modifiers
@public
method toString
static toString: () => string;
interface Component
interface Component<S = unknown> extends CoreView, ChildViewsSupport, ViewStateSupport, ClassNamesSupport, TargetActionSupport, ActionSupport, ViewMixin, ComponentMethods {}
A component is a reusable UI element that consists of a
.hbs
template and an optional JavaScript class that defines its behavior. For example, someone might make abutton
in the template and handle the click behavior in the JavaScript file that shares the same name as the template.Components are broken down into two categories:
- Components _without_ JavaScript, that are based only on a template. These are called Template-only or TO components. - Components _with_ JavaScript, which consist of a template and a backing class.
Ember ships with two types of JavaScript classes for components:
1. Glimmer components, imported from
@glimmer/component
, which are the default component's for Ember Octane (3.15) and more recent editions. 2. Classic components, imported from@ember/component
, which were the default for older editions of Ember (pre 3.15).Below is the documentation for Classic components. If you are looking for the API documentation for Template-only or Glimmer components, it is [available here](/ember/release/modules/@glimmer%2Fcomponent).
## Defining a Classic Component
If you want to customize the component in order to handle events, transform arguments or maintain internal state, you implement a subclass of
Component
.One example is to add computed properties to your component:
```app/components/person-profile.js import Component from '@ember/component';
export default Component.extend({ displayName: computed('person.title', 'person.firstName', 'person.lastName', function() { let { title, firstName, lastName } = this.person;
if (title) { return
${title} ${lastName}
; } else { return${firstName} ${lastName}
; } }) }); ```And then use it in the component's template:
```app/templates/components/person-profile.hbs {{this.displayName}} {{yield}} ```
## Customizing a Classic Component's HTML Element in JavaScript
### HTML Tag
The default HTML tag name used for a component's HTML representation is
div
. This can be customized by setting thetagName
property.Consider the following component class:
```app/components/emphasized-paragraph.js import Component from '@ember/component';
export default Component.extend({ tagName: 'em' }); ```
When invoked, this component would produce output that looks something like this:
```html ```
### HTML
class
AttributeThe HTML
class
attribute of a component's tag can be set by providing aclassNames
property that is set to an array of strings:```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ classNames: ['my-class', 'my-other-class'] }); ```
Invoking this component will produce output that looks like this:
```html ```
class
attribute values can also be set by providing aclassNameBindings
property set to an array of properties names for the component. The return value of these properties will be added as part of the value for the components'sclass
attribute. These properties can be computed properties:```app/components/my-widget.js import Component from '@ember/component'; import { computed } from '@ember/object';
export default Component.extend({ classNames: ['my-class', 'my-other-class'], classNameBindings: ['propertyA', 'propertyB'],
propertyA: 'from-a', propertyB: computed(function() { if (someLogic) { return 'from-b'; } }) }); ```
Invoking this component will produce HTML that looks like:
```html ```
Note that
classNames
andclassNameBindings
is in addition to theclass
attribute passed with the angle bracket invocation syntax. Therefore, if this component was invoked like so:```handlebars ```
The resulting HTML will look similar to this:
```html ```
If the value of a class name binding returns a boolean the property name itself will be used as the class name if the property is true. The class name will not be added if the value is
false
orundefined
.```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ classNameBindings: ['hovered'],
hovered: true }); ```
Invoking this component will produce HTML that looks like:
```html ```
### Custom Class Names for Boolean Values
When using boolean class name bindings you can supply a string value other than the property name for use as the
class
HTML attribute by appending the preferred value after a ":" character when defining the binding:```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ classNameBindings: ['awesome:so-very-cool'],
awesome: true }); ```
Invoking this component will produce HTML that looks like:
```html ```
Boolean value class name bindings whose property names are in a camelCase-style format will be converted to a dasherized format:
```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ classNameBindings: ['isUrgent'],
isUrgent: true }); ```
Invoking this component will produce HTML that looks like:
```html ```
Class name bindings can also refer to object values that are found by traversing a path relative to the component itself:
```app/components/my-widget.js import Component from '@ember/component'; import EmberObject from '@ember/object';
export default Component.extend({ classNameBindings: ['messages.empty'],
messages: EmberObject.create({ empty: true }) }); ```
Invoking this component will produce HTML that looks like:
```html ```
If you want to add a class name for a property which evaluates to true and and a different class name if it evaluates to false, you can pass a binding like this:
```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ classNameBindings: ['isEnabled:enabled:disabled'], isEnabled: true }); ```
Invoking this component will produce HTML that looks like:
```html ```
When isEnabled is
false
, the resulting HTML representation looks like this:```html ```
This syntax offers the convenience to add a class if a property is
false
:```app/components/my-widget.js import Component from '@ember/component';
// Applies no class when isEnabled is true and class 'disabled' when isEnabled is false export default Component.extend({ classNameBindings: ['isEnabled::disabled'], isEnabled: true }); ```
Invoking this component when the
isEnabled
property is true will produce HTML that looks like:```html ```
Invoking it when the
isEnabled
property on the component isfalse
will produce HTML that looks like:```html ```
Updates to the value of a class name binding will result in automatic update of the HTML
class
attribute in the component's rendered HTML representation. If the value becomesfalse
orundefined
the class name will be removed.Both
classNames
andclassNameBindings
are concatenated properties. See [EmberObject](/ember/release/classes/EmberObject) documentation for more information about concatenated properties.### Other HTML Attributes
The HTML attribute section of a component's tag can be set by providing an
attributeBindings
property set to an array of property names on the component. The return value of these properties will be used as the value of the component's HTML associated attribute:```app/components/my-anchor.js import Component from '@ember/component';
export default Component.extend({ tagName: 'a', attributeBindings: ['href'],
href: 'http://google.com' }); ```
Invoking this component will produce HTML that looks like:
```html ```
One property can be mapped on to another by placing a ":" between the source property and the destination property:
```app/components/my-anchor.js import Component from '@ember/component';
export default Component.extend({ tagName: 'a', attributeBindings: ['url:href'],
url: 'http://google.com' }); ```
Invoking this component will produce HTML that looks like:
```html ```
HTML attributes passed with angle bracket invocations will take precedence over those specified in
attributeBindings
. Therefore, if this component was invoked like so:```handlebars <MyAnchor href="http://bing.com" @url="http://google.com" /> ```
The resulting HTML will looks like this:
```html ```
Note that the
href
attribute is ultimately set tohttp://bing.com
, despite it having attribute binidng to theurl
property, which was set tohttp://google.com
.Namespaced attributes (e.g.
xlink:href
) are supported, but have to be mapped, since:
is not a valid character for properties in Javascript:```app/components/my-use.js import Component from '@ember/component';
export default Component.extend({ tagName: 'use', attributeBindings: ['xlinkHref:xlink:href'],
xlinkHref: '#triangle' }); ```
Invoking this component will produce HTML that looks like:
```html <use xlink:href="#triangle"> ```
If the value of a property monitored by
attributeBindings
is a boolean, the attribute will be present or absent depending on the value:```app/components/my-text-input.js import Component from '@ember/component';
export default Component.extend({ tagName: 'input', attributeBindings: ['disabled'],
disabled: false }); ```
Invoking this component will produce HTML that looks like:
```html ```
attributeBindings
can refer to computed properties:```app/components/my-text-input.js import Component from '@ember/component'; import { computed } from '@ember/object';
export default Component.extend({ tagName: 'input', attributeBindings: ['disabled'],
disabled: computed(function() { if (someLogic) { return true; } else { return false; } }) }); ```
To prevent setting an attribute altogether, use
null
orundefined
as the value of the property used inattributeBindings
:```app/components/my-text-input.js import Component from '@ember/component';
export default Component.extend({ tagName: 'form', attributeBindings: ['novalidate'], novalidate: null }); ```
Updates to the property of an attribute binding will result in automatic update of the HTML attribute in the component's HTML output.
attributeBindings
is a concatenated property. See [EmberObject](/ember/release/classes/EmberObject) documentation for more information about concatenated properties.## Layouts
The
layout
property can be used to dynamically specify a template associated with a component class, instead of relying on Ember to link together a component class and a template based on file names.In general, applications should not use this feature, but it's commonly used in addons for historical reasons.
The
layout
property should be set to the default export of a template module, which is the name of a template file without the.hbs
extension.```app/templates/components/person-profile.hbs Person's Title {{yield}} ```
```app/components/person-profile.js import Component from '@ember/component'; import layout from '../templates/components/person-profile';
export default Component.extend({ layout }); ```
If you invoke the component:
```handlebars Chief Basket Weaver Fisherman Industries ```
or
```handlebars {{#person-profile}} Chief Basket Weaver Fisherman Industries {{/person-profile}} ```
It will result in the following HTML output:
```html Person's Title Chief Basket Weaver Fisherman Industries ```
## Handling Browser Events
There are two ways to handle user-initiated events:
### Using the
on
modifier to capture browser eventsIn a component's template, you can attach an event handler to any element with the
on
modifier:```handlebars <button {{on 'click' this.doSomething}} /> ```
This will call the function on your component:
```js import Component from '@ember/component';
export default class ExampleComponent extends Component { doSomething = (event) => { //
event
is the native click Event console.log('clicked on the button'); }; }); ```See the [Guide on Component event handlers](https://guides.emberjs.com/release/components/component-state-and-actions/#toc_html-modifiers-and-actions) and the [API docs for
on
](../Ember.Templates.helpers/methods/on?anchor=on) for more details.### Event Handler Methods
Components can also respond to user-initiated events by implementing a method that matches the event name. This approach is appropriate when the same event should be handled by all instances of the same component.
An event object will be passed as the argument to the event handler method.
```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ click(event) { //
event.target
is either the component's element or one of its children let tag = event.target.tagName.toLowerCase(); console.log('clicked on a<${tag}>
HTML element!'); } }); ```In this example, whenever the user clicked anywhere inside the component, it will log a message to the console.
It is possible to handle event types other than
click
by implementing the following event handler methods. In addition, custom events can be registered by usingApplication.customEvents
.Touch events:
touchStart
touchMove
touchEnd
touchCancel
Keyboard events:
keyDown
keyUp
keyPress
Mouse events:
mouseDown
mouseUp
contextMenu
click
doubleClick
focusIn
focusOut
Form events:
submit
change
focusIn
focusOut
input
Drag and drop events:
dragStart
drag
dragEnter
dragLeave
dragOver
dragEnd
drop
Component Ember.CoreView Ember.TargetActionSupport Ember.ClassNamesSupport Ember.ActionSupport Ember.ViewMixin Ember.ViewStateSupport
Modifiers
@public
namespace @ember/-internals/glimmer/lib/component-managers/curly
module '@ember/-internals/glimmer/lib/component-managers/curly' {}
variable ARGS
const ARGS: string;
variable BOUNDS
const BOUNDS: Symbol;
variable CURLY_CAPABILITIES
const CURLY_CAPABILITIES: InternalComponentCapabilities;
variable CURLY_COMPONENT_MANAGER
const CURLY_COMPONENT_MANAGER: CurlyComponentManager;
variable DIRTY_TAG
const DIRTY_TAG: Symbol;
variable HAS_BLOCK
const HAS_BLOCK: string;
variable IS_DISPATCHING_ATTRS
const IS_DISPATCHING_ATTRS: Symbol;
function initialRenderInstrumentDetails
initialRenderInstrumentDetails: (component: any) => any;
function isCurlyManager
isCurlyManager: (manager: object) => boolean;
function processComponentInitializationAssertions
processComponentInitializationAssertions: ( component: Component, props: any) => void;
function rerenderInstrumentDetails
rerenderInstrumentDetails: (component: any) => any;
class CurlyComponentManager
class CurlyComponentManager implements WithCreateInstance<ComponentStateBucket>, WithDynamicLayout<ComponentStateBucket, RuntimeResolver>, WithDynamicTagName<ComponentStateBucket> {}
method create
create: ( owner: Owner, ComponentClass: ComponentFactory, args: VMArguments, { isInteractive }: Environment, dynamicScope: DynamicScope, callerSelfRef: Reference, hasBlock: boolean) => ComponentStateBucket;
method didCreate
didCreate: ({ component, isInteractive }: ComponentStateBucket) => void;
method didCreateElement
didCreateElement: ( { component, classRef, isInteractive, rootRef }: ComponentStateBucket, element: Element, operations: ElementOperations) => void;
method didRenderLayout
didRenderLayout: (bucket: ComponentStateBucket, bounds: Bounds) => void;
method didUpdate
didUpdate: ({ component, isInteractive }: ComponentStateBucket) => void;
method didUpdateLayout
didUpdateLayout: (bucket: ComponentStateBucket) => void;
method getCapabilities
getCapabilities: () => InternalComponentCapabilities;
method getDebugName
getDebugName: (definition: ComponentFactory) => string;
method getDestroyable
getDestroyable: (bucket: ComponentStateBucket) => Destroyable;
method getDynamicLayout
getDynamicLayout: (bucket: ComponentStateBucket) => CompilableProgram | null;
method getSelf
getSelf: ({ rootRef }: ComponentStateBucket) => Reference;
method getTagName
getTagName: (state: ComponentStateBucket) => Nullable<string>;
method prepareArgs
prepareArgs: ( ComponentClass: ComponentFactory, args: VMArguments) => PreparedArguments;
method templateFor
protected templateFor: (component: Component) => CompilableProgram | null;
method update
update: (bucket: ComponentStateBucket) => void;
namespace @ember/-internals/glimmer/lib/component-managers/mount
module '@ember/-internals/glimmer/lib/component-managers/mount' {}
class MountDefinition
class MountDefinition implements ComponentDefinition {}
constructor
constructor(resolvedName: string);
property capabilities
capabilities: any;
property compilable
compilable: null;
property handle
handle: number;
property manager
manager: MountManager;
property resolvedName
resolvedName: string;
property state
state: EngineDefinitionState;
namespace @ember/-internals/glimmer/lib/component-managers/outlet
module '@ember/-internals/glimmer/lib/component-managers/outlet' {}
function createRootOutlet
createRootOutlet: (outletView: OutletView) => OutletComponentDefinition;
class OutletComponentDefinition
class OutletComponentDefinition implements ComponentDefinition< OutletDefinitionState, OutletInstanceState, OutletComponentManager > {}
constructor
constructor(state: OutletDefinitionState, manager?: OutletComponentManager);
property capabilities
capabilities: CapabilityMask;
property compilable
compilable: CompilableProgram;
property handle
handle: number;
property manager
manager: OutletComponentManager;
property resolvedName
resolvedName: string;
property state
state: OutletDefinitionState;
interface OutletDefinitionState
interface OutletDefinitionState {}
property controller
controller: unknown;
property model
model: unknown;
property name
name: string;
property ref
ref: Reference<OutletState | undefined>;
property template
template: Template;
namespace @ember/-internals/glimmer/lib/component-managers/root
module '@ember/-internals/glimmer/lib/component-managers/root' {}
variable ROOT_CAPABILITIES
const ROOT_CAPABILITIES: InternalComponentCapabilities;
class RootComponentDefinition
class RootComponentDefinition implements ComponentDefinition {}
constructor
constructor(component: Component<unknown>);
property capabilities
capabilities: any;
property compilable
compilable: null;
property handle
handle: number;
property manager
manager: RootComponentManager;
property resolvedName
resolvedName: string;
property state
state: {};
namespace @ember/-internals/glimmer/lib/components/abstract-input
module '@ember/-internals/glimmer/lib/components/abstract-input' {}
function valueFrom
valueFrom: (reference?: Reference<unknown>) => Value;
class AbstractInput
abstract class AbstractInput extends InternalComponent {}
property value
value: {};
method change
change: (event: Event) => void;
The
change
andinput
actions need to be overridden in theInput
subclass. Unfortunately, some ember-source builds currently uses babel loose mode to transpile its classes. Having the@action
decorator on the super class creates a getter on the prototype, and when the subclass overrides the method, the loose mode transpilation would emit something likeSubclass.prototype['change'] = function change() { ... }
, which fails becauseprototype['change']
is getter-only/readonly. The correct solution is to useObject.defineProperty(prototype, 'change', ...)
but that requires disabling loose mode. For now, the workaround is to add the decorator only on the subclass. This is more of a configuration issue on our own builds and doesn't really affect apps.
method input
input: (event: Event) => void;
method isVirtualEventListener
protected isVirtualEventListener: ( name: string, _listener: Function) => _listener is VirtualEventListener;
method keyUp
keyUp: (event: KeyboardEvent) => void;
method listenerFor
protected listenerFor: (name: string) => EventListener;
method validateArguments
validateArguments: () => void;
method valueDidChange
valueDidChange: (event: Event) => void;
namespace @ember/-internals/glimmer/lib/components/input
module '@ember/-internals/glimmer/lib/components/input' {}
namespace @ember/-internals/glimmer/lib/components/internal
module '@ember/-internals/glimmer/lib/components/internal' {}
function opaquify
opaquify: ( constructor: InternalComponentConstructor, template: TemplateFactory) => OpaqueInternalComponentConstructor;
class InternalComponent
class InternalComponent {}
constructor
constructor(owner: InternalOwner, args: CapturedArguments, caller: {});
property args
protected readonly args: CapturedArguments;
property caller
protected readonly caller: {};
property class
readonly class: string;
The default HTML class attribute. Similar to the above, we don't _need_ them, they are just added for compatibility as it's similarly hard to tell if people rely on it in their CSS etc, and it doens't really hurt.
property id
readonly id: string;
The default HTML id attribute. We don't really _need_ one, this is just added for compatibility as it's hard to tell if people rely on it being present, and it doens't really hurt.
However, don't rely on this internally, like passing it to
getElementId
. This can be (and often is) overriden by passing anid
attribute on the invocation, which shadows this default id via...attributes
.
property owner
protected owner: InternalOwner;
method isSupportedArgument
protected isSupportedArgument: (_name: string) => boolean;
method listenerFor
protected listenerFor: (name: string) => EventListener;
method named
protected named: (name: string) => unknown;
method onUnsupportedArgument
protected onUnsupportedArgument: (_name: string) => void;
method positional
protected positional: (index: number) => unknown;
method toString
static toString: () => string;
method validateArguments
protected validateArguments: () => void;
interface InternalComponentConstructor
interface InternalComponentConstructor< T extends InternalComponent = InternalComponent> {}
property prototype
prototype: T;
method toString
toString: () => string;
construct signature
new (owner: InternalOwner, args: CapturedArguments, caller: unknown): T;
interface OpaqueInternalComponentConstructor
interface OpaqueInternalComponentConstructor {}
property [OPAQUE_INTERNAL_COMPONENT_CONSTRUCTOR]
[OPAQUE_INTERNAL_COMPONENT_CONSTRUCTOR]: true;
method create
create: () => never;
method toString
toString: () => string;
type EventListener
type EventListener = (event: Event) => void;
namespace @ember/-internals/glimmer/lib/components/link-to
module '@ember/-internals/glimmer/lib/components/link-to' {}
namespace @ember/-internals/glimmer/lib/components/textarea
module '@ember/-internals/glimmer/lib/components/textarea' {}
namespace @ember/-internals/glimmer/lib/dom
module '@ember/-internals/glimmer/lib/dom' {}
namespace @ember/-internals/glimmer/lib/environment
module '@ember/-internals/glimmer/lib/environment' {}
class EmberEnvironmentDelegate
class EmberEnvironmentDelegate implements EnvironmentDelegate {}
constructor
constructor(owner: InternalOwner, isInteractive: boolean);
property enableDebugTooling
enableDebugTooling: boolean;
property isInteractive
isInteractive: boolean;
property owner
owner: InternalOwner;
method onTransactionCommit
onTransactionCommit: () => void;
namespace @ember/-internals/glimmer/lib/glimmer-tracking-docs
module '@ember/-internals/glimmer/lib/glimmer-tracking-docs' {}
namespace @ember/-internals/glimmer/lib/helper
module '@ember/-internals/glimmer/lib/helper' {}
variable CLASSIC_HELPER_MANAGER
const CLASSIC_HELPER_MANAGER: any;
variable RECOMPUTE_TAG
const RECOMPUTE_TAG: Symbol;
variable SIMPLE_CLASSIC_HELPER_MANAGER
const SIMPLE_CLASSIC_HELPER_MANAGER: SimpleClassicHelperManager;
function helper
helper: { <P extends DefaultPositional, N extends object, R = unknown>( helperFn: (positional: P, named: N) => R ): FunctionBasedHelper<{ Args: { Positional: P; Named: N }; Return: R }>; <S>( helperFn: ( positional: GetOr<GetOr<S, 'Args', {}>, 'Positional', DefaultPositional>, named: GetOr<GetOr<S, 'Args', {}>, 'Named', object> ) => GetOr<S, 'Return', unknown> ): FunctionBasedHelper<S>;};
In many cases it is not necessary to use the full
Helper
class. Thehelper
method create pure-function helpers without instances. For example:```app/helpers/format-currency.js import { helper } from '@ember/component/helper';
export default helper(function([cents], {currency}) { return
${currency}${cents * 0.01}
; }); ```Parameter helper
The helper function helper @ember/component/helper
1.13.0
Modifiers
@public
function isClassicHelper
isClassicHelper: (obj: object) => boolean;
class FunctionBasedHelperInstance
abstract class FunctionBasedHelperInstance<S> extends Helper<S> {}
class Helper
class Helper<S = unknown> extends FrameworkObject {}
property [IS_CLASSIC_HELPER]
static [IS_CLASSIC_HELPER]: boolean;
property [RECOMPUTE_TAG]
[RECOMPUTE_TAG]: DirtyableTag;
property helper
static helper: { <P extends DefaultPositional, N extends object, R = unknown>( helperFn: (positional: P, named: N) => R ): FunctionBasedHelper<{ Args: { Positional: P; Named: N }; Return: R }>; <S>( helperFn: ( positional: GetOr< GetOr<S, 'Args', {}>, 'Positional', DefaultPositional >, named: GetOr<GetOr<S, 'Args', {}>, 'Named', object> ) => GetOr<S, 'Return', unknown> ): FunctionBasedHelper<S>;};
Deprecated
property isHelperFactory
static isHelperFactory: boolean;
method init
init: (properties: object | undefined) => void;
method recompute
recompute: () => void;
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:```app/helpers/current-user-email.js import Helper from '@ember/component/helper' import { service } from '@ember/service' import { observer } from '@ember/object'
export default Helper.extend({ session: service(),
onNewUser: observer('session.currentUser', function() { this.recompute(); }),
compute() { return this.get('session.currentUser.email'); } }); ```
recompute
1.13.0
Modifiers
@public
interface Helper
interface Helper<S = unknown> {}
Ember Helpers are functions that can compute values, and are used in templates. For example, this code calls a helper named
format-currency
:```app/templates/application.hbs <Cost @cents={{230}} /> ```
```app/components/cost.hbs {{format-currency currency="$"}} ```
Additionally a helper can be called as a nested helper. In this example, we show the formatted currency value if the
showMoney
named argument is truthy.```handlebars {{if (format-currency currency="$")}} ```
Helpers defined using a class must provide a
compute
function. For example:```app/helpers/format-currency.js import Helper from '@ember/component/helper';
export default class extends Helper { compute([cents], { 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 and will accept injected dependencies.
Additionally, class helpers can call
recompute
to force a new computation.Helper CoreObject
1.13.0
Modifiers
@public
method compute
compute: (positional: Positional<S>, named: Named<S>) => Return<S>;
Override this function when writing a class-based helper.
compute
Parameter positional
The positional arguments to the helper
Parameter named
The named arguments to the helper
1.13.0
Modifiers
@public
interface HelperFactory
interface HelperFactory<T> {}
property isHelperFactory
isHelperFactory: true;
method create
create: () => T;
interface HelperInstance
interface HelperInstance<S> {}
property [RECOMPUTE_TAG]
[RECOMPUTE_TAG]: DirtyableTag;
method compute
compute: (positional: Positional<S>, named: Named<S>) => Return<S>;
method destroy
destroy: () => void;
interface SimpleHelper
interface SimpleHelper<S> {}
property compute
compute: (positional: Positional<S>, named: Named<S>) => Return<S>;
type FunctionBasedHelper
type FunctionBasedHelper<S> = abstract new () => FunctionBasedHelperInstance<S>;
The type of a function-based helper.
This is *not* user-constructible: it is exported only so that the type returned by the
helper
function can be named (and indeed can be exported likeexport default helper(...)
safely).
namespace @ember/-internals/glimmer/lib/helpers/-disallow-dynamic-resolution
module '@ember/-internals/glimmer/lib/helpers/-disallow-dynamic-resolution' {}
variable _default
const _default: {};
namespace @ember/-internals/glimmer/lib/helpers/-in-element-null-check
module '@ember/-internals/glimmer/lib/helpers/-in-element-null-check' {}
variable _default
const _default: {};
namespace @ember/-internals/glimmer/lib/helpers/-normalize-class
module '@ember/-internals/glimmer/lib/helpers/-normalize-class' {}
variable _default
const _default: {};
namespace @ember/-internals/glimmer/lib/helpers/-resolve
module '@ember/-internals/glimmer/lib/helpers/-resolve' {}
variable _default
const _default: {};
namespace @ember/-internals/glimmer/lib/helpers/-track-array
module '@ember/-internals/glimmer/lib/helpers/-track-array' {}
variable _default
const _default: {};
This reference is used to get the
[]
tag of iterables, so we can trigger updates to{{each}}
when it changes. It is put into place by a template transform at build time, similar to the (-each-in) helper
namespace @ember/-internals/glimmer/lib/helpers/action
module '@ember/-internals/glimmer/lib/helpers/action' {}
variable _default
const _default: {};
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 }} <div onclick={{action "save"}}> {{! 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. Its 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 immediately 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, in the attribute context:
```handlebars {{! An example of attribute context }} <div onclick={{action "save"}}> ```
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 and still execute in the correct context.Here is an example action handler on a component:
```app/components/my-component.js import Component from '@glimmer/component'; import { action } from '@ember/object';
export default class extends Component { save() { this.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 asdestroy
. Two options can be passed to theaction
helper when it is used in this way.target=someProperty
will look tosomeProperty
instead of the current context for theactions
hash. This can be useful when targeting a service for actions.value="target.value"
will read the pathtarget.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 are presented in JavaScript as callbacks, and are invoked like any other JavaScript function.
For example
```app/components/update-name.js import Component from '@glimmer/component'; import { action } from '@ember/object';
export default class extends Component { setName(model, name) { model.set('name', name); } } ```
```app/components/update-name.hbs {{input on-input=(action (action 'setName' @model) value="target.value")}} ```
The first argument (
@model
) was curried over, and the run-time argument (event
) becomes a second argument. Action calls can 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 withon-input
above. For example:```app/components/my-input.js import Component from '@glimmer/component'; import { action } from '@ember/object';
export default class extends Component { setName(model, name) { model.set('name', name); } } ```
```handlebars <MyInput @submit={{action 'setName' @model}} /> ```
or
```handlebars {{my-input submit=(action 'setName' @model)}} ```
```app/components/my-component.js import Component from '@ember/component';
export default Component.extend({ click() { // Note that model is not passed, it was curried in the template this.submit('bob'); } }); ```
### Attaching actions to DOM elements
The third context of the
{{action}}
helper can be called "element space". For example:```handlebars {{! An example of element space }} <div {{action "save"}}> ```
Used this way, the
{{action}}
helper provides a useful shortcut for registering an HTML element in 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. Note that the closure style actions cannot.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 thepreventDefault=false
option to the{{action}}
helper:```handlebars <div {{action "sayHello" preventDefault=false}}> ```
To disable bubbling, pass
bubbles=false
to the helper:```handlebars <button {{action 'edit' post bubbles=false}}>Edit ```
To disable bubbling with closure style actions you must create your own wrapper helper that makes use of
event.stopPropagation()
:```handlebars <div onclick={{disable-bubbling (action "sayHello")}}>Hello ```
```app/helpers/disable-bubbling.js import { helper } from '@ember/component/helper';
export function disableBubbling([action]) { return function(event) { event.stopPropagation(); return action(event); }; } export default helper(disableBubbling); ```
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 ["Responding to Browser Events"](/ember/release/classes/Component) in the documentation for
Component
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 DOMclick
events. You can supply anon
option to the helper to specify a different DOM event name:```handlebars <div {{action "anActionName" on="doubleClick"}}> click me ```
See ["Event Names"](/ember/release/classes/Component) 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 events with pressed modifier keys. You can supply anallowedKeys
option to specify which keys should not be ignored.```handlebars <div {{action "anActionName" allowedKeys="alt"}}> 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 <div {{action "anActionName" allowedKeys="any"}}> 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:```app/templates/application.hbs <div {{action "anActionName" target=someService}}> click me ```
```app/controllers/application.js import Controller from '@ember/controller'; import { service } from '@ember/service';
export default class extends Controller { someService; } ```
action
Modifiers
@public
Deprecated
Ember.Templates.helpers
variable ACTIONS
const ACTIONS: WeakSet<object>;
namespace @ember/-internals/glimmer/lib/helpers/array
module '@ember/-internals/glimmer/lib/helpers/array' {}
namespace @ember/-internals/glimmer/lib/helpers/component
module '@ember/-internals/glimmer/lib/helpers/component' {}
namespace @ember/-internals/glimmer/lib/helpers/concat
module '@ember/-internals/glimmer/lib/helpers/concat' {}
namespace @ember/-internals/glimmer/lib/helpers/each-in
module '@ember/-internals/glimmer/lib/helpers/each-in' {}
variable _default
const _default: {};
class EachInWrapper
class EachInWrapper {}
The
{{each-in}}
helper loops over properties on an object.For example, given this component definition:
```app/components/developer-details.js import Component from '@glimmer/component'; import { tracked } from '@glimmer/tracking';
export default class extends Component { developer = { "name": "Shelly Sails", "age": 42 }; } ```
This template would display all properties on the
developer
object in a list:```app/components/developer-details.hbs {{#each-in this.developer as |key value|}} {{key}}: {{value}} {{/each-in}} ```
Outputting their name and age:
```html name: Shelly Sails age: 42 ```
each-in Ember.Templates.helpers
2.1.0
Modifiers
@public
constructor
constructor(inner: {});
property inner
inner: {};
namespace @ember/-internals/glimmer/lib/helpers/fn
module '@ember/-internals/glimmer/lib/helpers/fn' {}
namespace @ember/-internals/glimmer/lib/helpers/get
module '@ember/-internals/glimmer/lib/helpers/get' {}
namespace @ember/-internals/glimmer/lib/helpers/hash
module '@ember/-internals/glimmer/lib/helpers/hash' {}
namespace @ember/-internals/glimmer/lib/helpers/helper
module '@ember/-internals/glimmer/lib/helpers/helper' {}
namespace @ember/-internals/glimmer/lib/helpers/if-unless
module '@ember/-internals/glimmer/lib/helpers/if-unless' {}
namespace @ember/-internals/glimmer/lib/helpers/internal-helper
module '@ember/-internals/glimmer/lib/helpers/internal-helper' {}
function internalHelper
internalHelper: (helper: Helper<InternalOwner>) => HelperDefinitionState;
namespace @ember/-internals/glimmer/lib/helpers/log
module '@ember/-internals/glimmer/lib/helpers/log' {}
namespace @ember/-internals/glimmer/lib/helpers/modifier
module '@ember/-internals/glimmer/lib/helpers/modifier' {}
namespace @ember/-internals/glimmer/lib/helpers/mut
module '@ember/-internals/glimmer/lib/helpers/mut' {}
variable _default
const _default: {};
The
mut
helper lets you __clearly specify__ that a childComponent
can update the (mutable) value passed to it, which will __change the value of the parent component__.To specify that a parameter is mutable, when invoking the child
Component
:```handlebars <MyChild @childClickCount={{fn (mut totalClicks)}} /> ```
or
```handlebars {{my-child childClickCount=(mut totalClicks)}} ```
The child
Component
can then modify the parent's value just by modifying its own property:```javascript // my-child.js export default Component.extend({ click() { this.incrementProperty('childClickCount'); } }); ```
Note that for curly components (
{{my-component}}
) the bindings are already mutable, making themut
unnecessary.Additionally, the
mut
helper can be combined with thefn
helper to mutate a value. For example:```handlebars <MyChild @childClickCount={{this.totalClicks}} @click-count-change={{fn (mut totalClicks))}} /> ```
or
```handlebars {{my-child childClickCount=totalClicks click-count-change=(fn (mut totalClicks))}} ```
The child
Component
would invoke the function with the new click value:```javascript // my-child.js export default Component.extend({ click() { this.get('click-count-change')(this.get('childClickCount') + 1); } }); ```
The
mut
helper changes thetotalClicks
value to what was provided as thefn
argument.The
mut
helper, when used withfn
, will return a function that sets the value passed tomut
to its first argument. As an example, we can create a button that increments a value passing the value directly to thefn
:```handlebars {{! inc helper is not provided by Ember }} <button onclick={{fn (mut count) (inc count)}}> Increment count ```
mut
Parameter attr
the "two-way" attribute that can be modified. Ember.Templates.helpers
Modifiers
@public
namespace @ember/-internals/glimmer/lib/helpers/page-title
module '@ember/-internals/glimmer/lib/helpers/page-title' {}
namespace @ember/-internals/glimmer/lib/helpers/readonly
module '@ember/-internals/glimmer/lib/helpers/readonly' {}
variable _default
const _default: {};
The
readonly
helper let's you specify that a binding is one-way only, instead of two-way. When you pass areadonly
binding from an outer context (e.g. parent component), to to an inner context (e.g. child component), you are saying that changing that property in the inner context does not change the value in the outer context.To specify that a binding is read-only, when invoking the child
Component
:```app/components/my-parent.js export default Component.extend({ totalClicks: 3 }); ```
```app/templates/components/my-parent.hbs {{log totalClicks}} // -> 3 <MyChild @childClickCount={{readonly totalClicks}} /> ``` ``` {{my-child childClickCount=(readonly totalClicks)}} ```
Now, when you update
childClickCount
:```app/components/my-child.js export default Component.extend({ click() { this.incrementProperty('childClickCount'); } }); ```
The value updates in the child component, but not the parent component:
```app/templates/components/my-child.hbs {{log childClickCount}} //-> 4 ```
```app/templates/components/my-parent.hbs {{log totalClicks}} //-> 3 <MyChild @childClickCount={{readonly totalClicks}} /> ``` or ```app/templates/components/my-parent.hbs {{log totalClicks}} //-> 3 {{my-child childClickCount=(readonly totalClicks)}} ```
### Objects and Arrays
When passing a property that is a complex object (e.g. object, array) instead of a primitive object (e.g. number, string), only the reference to the object is protected using the readonly helper. This means that you can change properties of the object both on the parent component, as well as the child component. The
readonly
binding behaves similar to theconst
keyword in JavaScript.Let's look at an example:
First let's set up the parent component:
```app/components/my-parent.js import Component from '@ember/component';
export default Component.extend({ clicks: null,
init() { this._super(...arguments); this.set('clicks', { total: 3 }); } }); ```
```app/templates/components/my-parent.hbs {{log clicks.total}} //-> 3 <MyChild @childClicks={{readonly clicks}} /> ``` ```app/templates/components/my-parent.hbs {{log clicks.total}} //-> 3 {{my-child childClicks=(readonly clicks)}} ```
Now, if you update the
total
property ofchildClicks
:```app/components/my-child.js import Component from '@ember/component';
export default Component.extend({ click() { this.get('clicks').incrementProperty('total'); } }); ```
You will see the following happen:
```app/templates/components/my-parent.hbs {{log clicks.total}} //-> 4 <MyChild @childClicks={{readonly clicks}} /> ``` or ```app/templates/components/my-parent.hbs {{log clicks.total}} //-> 4 {{my-child childClicks=(readonly clicks)}} ```
```app/templates/components/my-child.hbs {{log childClicks.total}} //-> 4 ```
readonly
Parameter attr
the read-only attribute. Ember.Templates.helpers
namespace @ember/-internals/glimmer/lib/helpers/unbound
module '@ember/-internals/glimmer/lib/helpers/unbound' {}
variable _default
const _default: {};
The
{{unbound}}
helper disconnects the one-way binding of a property, essentially freezing its value at the moment of rendering. For example, in this example the display of the variablename
will not change even if it is set with a new value:```handlebars {{unbound this.name}} ```
Like any helper, the
unbound
helper can accept a nested helper expression. This allows for custom helpers to be rendered unbound:```handlebars {{unbound (some-custom-helper)}} {{unbound (capitalize this.name)}} {{! You can use any helper, including unbound, in a nested expression }} {{capitalize (unbound this.name)}} ```
The
unbound
helper only accepts a single argument, and it return an unbound value.unbound Ember.Templates.helpers
Modifiers
@public
namespace @ember/-internals/glimmer/lib/helpers/unique-id
module '@ember/-internals/glimmer/lib/helpers/unique-id' {}
namespace @ember/-internals/glimmer/lib/modifiers/action
module '@ember/-internals/glimmer/lib/modifiers/action' {}
variable _default
const _default: {};
variable ActionHelper
let ActionHelper: { registeredActions: Record<string, ActionState>; registerAction(actionState: ActionState): number; unregisterAction(actionState: ActionState): void;};
class ActionState
class ActionState {}
constructor
constructor( element: SimpleElement, owner: InternalOwner, actionId: number, actionArgs: any[], namedArgs: CapturedNamedArguments, positionalArgs: CapturedPositionalArguments);
property actionArgs
actionArgs: any;
property actionId
actionId: number;
property actionName
actionName: any;
property element
element: SimpleElement;
property eventName
eventName: any;
property implicitTarget
implicitTarget: any;
property namedArgs
namedArgs: CapturedNamedArguments;
property owner
owner: InternalOwner;
property positional
positional: CapturedPositionalArguments;
property tag
tag: UpdatableTag;
method getActionArgs
getActionArgs: () => any[];
method getEventName
getEventName: () => unknown;
method getTarget
getTarget: () => any;
method handler
handler: (event: Event) => boolean;
namespace @ember/-internals/glimmer/lib/modifiers/internal
module '@ember/-internals/glimmer/lib/modifiers/internal' {}
class InternalModifier
class InternalModifier {}
constructor
constructor(owner: InternalOwner, element: Element, args: CapturedArguments);
property args
protected readonly args: CapturedArguments;
property element
protected readonly element: Element;
property owner
protected owner: InternalOwner;
method install
install: () => void;
method named
protected named: (key: string) => unknown;
method positional
protected positional: (index: number) => unknown;
method remove
remove: () => void;
method toString
static toString: () => string;
class InternalModifierManager
abstract class InternalModifierManager implements ModifierManager<InternalModifierState, typeof InternalModifier> {}
constructor
constructor(ModifierClass: typeof InternalModifier, name: string);
method create
create: ( owner: InternalOwner, element: SimpleElement, _definition: unknown, args: CapturedArguments) => InternalModifierState;
method getDebugInstance
abstract getDebugInstance: (state: InternalModifierState) => unknown;
method getDebugName
getDebugName: () => string;
method getDestroyable
getDestroyable: ({ instance }: InternalModifierState) => Destroyable;
method getTag
getTag: () => null;
method install
install: ({ instance }: InternalModifierState) => void;
method update
update: () => void;
namespace @ember/-internals/glimmer/lib/modifiers/on
module '@ember/-internals/glimmer/lib/modifiers/on' {}
namespace @ember/-internals/glimmer/lib/renderer
module '@ember/-internals/glimmer/lib/renderer' {}
function renderSettled
renderSettled: () => RSVP.Promise<void>;
class DynamicScope
class DynamicScope implements GlimmerDynamicScope {}
constructor
constructor(view: View, outletState: Reference<OutletState>);
property outletState
outletState: Reference<OutletState>;
property view
view: View;
method child
child: () => DynamicScope;
method get
get: (key: 'outletState') => Reference<OutletState>;
method set
set: ( key: 'outletState', value: Reference<OutletState>) => Reference<OutletState>;
class Renderer
class Renderer {}
constructor
constructor( owner: InternalOwner, document: SimpleDocument, env: { isInteractive: boolean; hasDOM: boolean }, rootTemplate: TemplateFactory, viewRegistry: ViewRegistry, builder?: any);
property debugRenderTree
readonly debugRenderTree: DebugRenderTree;
method appendOutletView
appendOutletView: (view: OutletView, target: SimpleElement) => void;
method appendTo
appendTo: (view: Component, target: SimpleElement) => void;
method cleanupRootFor
cleanupRootFor: (view: unknown) => void;
method create
static create: (props: { _viewRegistry: any }) => Renderer;
method createElement
createElement: (tagName: string) => SimpleElement;
method destroy
destroy: () => void;
method getBounds
getBounds: (view: View) => { parentElement: SimpleElement; firstNode: SimpleNode; lastNode: SimpleNode;};
method getElement
getElement: (view: View) => Nullable<Element>;
method register
register: (view: any) => void;
method remove
remove: (view: Component) => void;
method rerender
rerender: () => void;
method unregister
unregister: (view: any) => void;
interface View
interface View {}
property [BOUNDS]
[BOUNDS]: Bounds | null;
property elementId
elementId: string | null;
property isDestroyed
isDestroyed: boolean;
property isDestroying
isDestroying: boolean;
property parentView
parentView: Nullable<View>;
property renderer
renderer: Renderer;
property tagName
tagName: string | null;
type IBuilder
type IBuilder = (env: Environment, cursor: Cursor) => ElementBuilder;
namespace @ember/-internals/glimmer/lib/resolver
module '@ember/-internals/glimmer/lib/resolver' {}
class ResolverImpl
class ResolverImpl implements RuntimeResolver<InternalOwner>, CompileTimeResolver<InternalOwner> {}
method lookupBuiltInHelper
lookupBuiltInHelper: (name: string) => HelperDefinitionState | null;
method lookupBuiltInModifier
lookupBuiltInModifier: { <K extends string>(name: K): ModifierDefinitionState; (name: string): null;};
method lookupComponent
lookupComponent: ( name: string, owner: InternalOwner) => ResolvedComponentDefinition | null;
method lookupHelper
lookupHelper: (name: string, owner: InternalOwner) => HelperDefinitionState;
method lookupModifier
lookupModifier: (name: string, owner: InternalOwner) => ModifierDefinitionState;
method lookupPartial
lookupPartial: () => null;
namespace @ember/-internals/glimmer/lib/setup-registry
module '@ember/-internals/glimmer/lib/setup-registry' {}
function setupApplicationRegistry
setupApplicationRegistry: (registry: Registry) => void;
function setupEngineRegistry
setupEngineRegistry: (registry: Registry) => void;
namespace @ember/-internals/glimmer/lib/syntax/in-element
module '@ember/-internals/glimmer/lib/syntax/in-element' {}
namespace @ember/-internals/glimmer/lib/syntax/let
module '@ember/-internals/glimmer/lib/syntax/let' {}
namespace @ember/-internals/glimmer/lib/syntax/mount
module '@ember/-internals/glimmer/lib/syntax/mount' {}
variable mountHelper
const mountHelper: {};
The
{{mount}}
helper lets you embed a routeless engine in a template. Mounting an engine will cause an instance to be booted and itsapplication
template to be rendered.For example, the following template mounts the
ember-chat
engine:```handlebars {{! application.hbs }} {{mount "ember-chat"}} ```
Additionally, you can also pass in a
model
argument that will be set as the engines model. This can be an existing object:``` {{mount 'admin' model=userSettings}} ```
Or an inline
hash
, and you can even pass components:``` Application template! {{mount 'admin' model=(hash title='Secret Admin' signInButton=(component 'sign-in-button') )}} ```
mount
Parameter name
Name of the engine to mount.
Parameter model
Object that will be set as the model of the engine. Ember.Templates.helpers
Modifiers
@public
namespace @ember/-internals/glimmer/lib/syntax/outlet
module '@ember/-internals/glimmer/lib/syntax/outlet' {}
variable outletHelper
const outletHelper: {};
The
{{outlet}}
helper lets you specify where a child route will render in your template. An important use of the{{outlet}}
helper is in your application'sapplication.hbs
file:```app/templates/application.hbs
<!-- this content will change based on the current route, which depends on the current URL --> {{outlet}}
```
See the [routing guide](https://guides.emberjs.com/release/routing/rendering-a-template/) for more information on how your
route
interacts with the{{outlet}}
helper. Note: Your content __will not render__ if there isn't an{{outlet}}
for it.outlet Ember.Templates.helpers
Modifiers
@public
namespace @ember/-internals/glimmer/lib/syntax/utils
module '@ember/-internals/glimmer/lib/syntax/utils' {}
function hashToArgs
hashToArgs: (hash: Core.Hash) => Core.Hash;
namespace @ember/-internals/glimmer/lib/template
module '@ember/-internals/glimmer/lib/template' {}
function isTemplateFactory
isTemplateFactory: ( template: Template | TemplateFactory) => template is TemplateFactory;
type OwnedTemplate
type OwnedTemplate = Template;
type StaticTemplate
type StaticTemplate = SerializedTemplateWithLazyBlock;
namespace @ember/-internals/glimmer/lib/template_registry
module '@ember/-internals/glimmer/lib/template_registry' {}
function getTemplate
getTemplate: (name: string) => TemplateFactory | void;
function getTemplates
getTemplates: () => TemplatesRegistry;
function hasTemplate
hasTemplate: (name: string) => boolean;
function setTemplate
setTemplate: (name: string, template: TemplateFactory) => TemplateFactory;
function setTemplates
setTemplates: (templates: TemplatesRegistry) => void;
interface TemplatesRegistry
interface TemplatesRegistry {}
index signature
[name: string]: TemplateFactory;
namespace @ember/-internals/glimmer/lib/templates/empty
module '@ember/-internals/glimmer/lib/templates/empty' {}
variable _default
const _default: any;
namespace @ember/-internals/glimmer/lib/templates/input
module '@ember/-internals/glimmer/lib/templates/input' {}
variable _default
const _default: any;
namespace @ember/-internals/glimmer/lib/templates/link-to
module '@ember/-internals/glimmer/lib/templates/link-to' {}
variable _default
const _default: any;
namespace @ember/-internals/glimmer/lib/templates/outlet
module '@ember/-internals/glimmer/lib/templates/outlet' {}
variable _default
const _default: any;
namespace @ember/-internals/glimmer/lib/templates/root
module '@ember/-internals/glimmer/lib/templates/root' {}
variable _default
const _default: any;
namespace @ember/-internals/glimmer/lib/templates/textarea
module '@ember/-internals/glimmer/lib/templates/textarea' {}
variable _default
const _default: any;
namespace @ember/-internals/glimmer/lib/utils/bindings
module '@ember/-internals/glimmer/lib/utils/bindings' {}
function createClassNameBindingRef
createClassNameBindingRef: ( rootRef: Reference<Component<unknown>>, microsyntax: string, operations: ElementOperations) => void;
function createColonClassNameBindingRef
createColonClassNameBindingRef: ( inner: Reference, truthy: string, falsy: string | undefined) => Reference<string>;
function createSimpleClassNameBindingRef
createSimpleClassNameBindingRef: ( inner: Reference, path?: string) => Reference<string>;
function installAttributeBinding
installAttributeBinding: ( component: Component, rootRef: Reference<Component<unknown>>, parsed: [string, string, boolean], operations: ElementOperations) => void;
function parseAttributeBinding
parseAttributeBinding: (microsyntax: string) => [string, string, boolean];
namespace @ember/-internals/glimmer/lib/utils/curly-component-state-bucket
module '@ember/-internals/glimmer/lib/utils/curly-component-state-bucket' {}
class ComponentStateBucket
class ComponentStateBucket {}
Represents the internal state of the component.
ComponentStateBucket
constructor
constructor( component: Component<unknown>, args: any, argsTag: Tag, finalizer: Finalizer, hasWrappedElement: boolean, isInteractive: boolean);
property args
args: any;
property argsRevision
argsRevision: Revision;
property argsTag
argsTag: Tag;
property classRef
classRef: any;
property component
component: Component<unknown>;
property finalizer
finalizer: Finalizer;
property hasWrappedElement
hasWrappedElement: boolean;
property isInteractive
isInteractive: boolean;
property rootRef
rootRef: Reference<Component<unknown>>;
method finalize
finalize: () => void;
method willDestroy
willDestroy: () => void;
namespace @ember/-internals/glimmer/lib/utils/debug-render-message
module '@ember/-internals/glimmer/lib/utils/debug-render-message' {}
variable debugRenderMessage
let debugRenderMessage: (renderingStack: string) => string;
namespace @ember/-internals/glimmer/lib/utils/iterator
module '@ember/-internals/glimmer/lib/utils/iterator' {}
function toIterator
toIterator: (iterable: unknown) => IteratorDelegate;
namespace @ember/-internals/glimmer/lib/utils/managers
module '@ember/-internals/glimmer/lib/utils/managers' {}
function setComponentManager
setComponentManager: <T extends object>( manager: (owner: InternalOwner) => ComponentManager<unknown>, obj: T) => T;
Associate a class with a component manager (an object that is responsible for coordinating the lifecycle events that occurs when invoking, rendering and re-rendering a component).
setComponentManager
Parameter factory
a function to create the owner for an object
Parameter obj
the object to associate with the componetn manager {Object} the same object passed in
Modifiers
@public
namespace @ember/-internals/glimmer/lib/utils/outlet
module '@ember/-internals/glimmer/lib/utils/outlet' {}
interface OutletState
interface OutletState {}
property outlets
outlets: { main: OutletState | undefined;};
Represents what, if any, should be rendered into the next {{outlet}} found at this level.
This used to be a dictionary of children outlets, including the {{outlet}} "main" outlet any {{outlet "named"}} named outlets. Since named outlets are not a thing anymore, this can now just be a single
child
.
property render
render: RenderState | undefined;
Represents what was rendered into this outlet.
property wasUsed
wasUsed?: undefined;
Deprecated
This tracks whether this outlet state actually made it onto the page somewhere. This was more of a problem when you can declare named outlets left and right, and anything can render into anywhere else. We want to warn users when you tried to render into somewhere that does not exist, but we don't know what named outlets exists until after we have rendered everything, so this was used to track these orphan renders.
This can still happen, if, according to the router, a route is active and so its template should be rendered, but the parent template is missing the
{{outlet}}
keyword, or that it was hidden by an{{#if}}
or something. I guess that is considered valid, because nothing checks for this anymore. seems valid for the parent to decide not to render a child template?
interface RenderState
interface RenderState {}
property controller
controller: unknown;
The controller (the self of the outlet component)
property into
into: undefined;
Deprecated
This used to specify "which parent route to render into", which is not a thing anymore.
property model
model: unknown;
The model (the resolved value of the model hook)
property name
name: string;
The name of the route/template
property outlet
outlet: 'main';
Deprecated
This used to specify "which named outlet in the parent template to render into", which is not a thing anymore.
property owner
owner: InternalOwner;
This is usually inherited from the parent (all the way up to the app instance). However, engines uses this to swap out the owner when crossing a mount point.
property template
template: Template | undefined;
template (the layout of the outlet component)
namespace @ember/-internals/glimmer/lib/utils/process-args
module '@ember/-internals/glimmer/lib/utils/process-args' {}
function processComponentArgs
processComponentArgs: (namedArgs: CapturedNamedArguments) => any;
namespace @ember/-internals/glimmer/lib/utils/serialization-first-node-helpers
module '@ember/-internals/glimmer/lib/utils/serialization-first-node-helpers' {}
namespace @ember/-internals/glimmer/lib/utils/string
module '@ember/-internals/glimmer/lib/utils/string' {}
function escapeExpression
escapeExpression: (string: unknown) => string;
function htmlSafe
htmlSafe: (str: string) => SafeString;
Use this method to indicate that a string should be rendered as HTML when the string is used in a template. To say this another way, strings marked with
htmlSafe
will not be HTML escaped.A word of warning - The
htmlSafe
method does not make the string safe; it only tells the framework to treat the string as if it is safe to render as HTML. If a string contains user inputs or other untrusted data, you must sanitize the string before using thehtmlSafe
method. Otherwise your code is vulnerable to [Cross-Site Scripting](https://owasp.org/www-community/attacks/DOM_Based_XSS). There are many open source sanitization libraries to choose from, both for front end and server-side sanitization.```javascript import { htmlSafe } from '@ember/template';
const someTrustedOrSanitizedString = "Hello!"
htmlSafe(someTrustedorSanitizedString) ```
htmlSafe @ember/template
Parameter str
The string to treat as trusted. {SafeString} A string that will not be HTML escaped by Handlebars.
Modifiers
@public
function isHTMLSafe
isHTMLSafe: (str: unknown) => str is SafeString;
Detects if a string was decorated using
htmlSafe
.```javascript import { htmlSafe, isHTMLSafe } from '@ember/template';
let plainString = 'plain string'; let safeString = htmlSafe('someValue');
isHTMLSafe(plainString); // false isHTMLSafe(safeString); // true ```
isHTMLSafe @ember/template {Boolean}
true
if the string was decorated withhtmlSafe
,false
otherwise.Modifiers
@public
class SafeString
class SafeString implements GlimmerSafeString {}
A wrapper around a string that has been marked as safe ("trusted"). **When rendered in HTML, Ember will not perform any escaping.**
Note:
1. This does not *make* the string safe; it means that some code in your application has *marked* it as safe using the
htmlSafe()
function.2. The only public API for getting a
SafeString
is callinghtmlSafe()
. It is *not* user-constructible.If a string contains user inputs or other untrusted data, you must sanitize the string before using the
htmlSafe
method. Otherwise your code is vulnerable to [Cross-Site Scripting][xss]. There are many open source sanitization libraries to choose from, both for front end and server-side sanitization.[xss]: https://owasp.org/www-community/attacks/DOM_Based_XSS
```javascript import { htmlSafe } from '@ember/template';
let someTrustedOrSanitizedString = "Hello!"
htmlSafe(someTrustedorSanitizedString); ```
@ember/template SafeString 4.12.0
Modifiers
@public
constructor
constructor(string: string);
method toHTML
toHTML: () => string;
Get the wrapped string as HTML to use without escaping.
toHTML
Returns
{String} the trusted string, without any escaping applied
Modifiers
@public
method toString
toString: () => string;
Get the string back to use as a string.
toString
Returns
{String} The string marked as trusted
Modifiers
@public
namespace @ember/-internals/glimmer/lib/utils/to-bool
module '@ember/-internals/glimmer/lib/utils/to-bool' {}
function toBool
toBool: (predicate: unknown) => boolean;
namespace @ember/-internals/glimmer/lib/views/outlet
module '@ember/-internals/glimmer/lib/views/outlet' {}
class OutletView
class OutletView {}
constructor
constructor( _environment: BootEnvironment, owner: InternalOwner, template: Template, namespace: any);
property namespace
namespace: any;
property owner
owner: InternalOwner;
property state
state: OutletDefinitionState;
property template
template: Template;
method appendTo
appendTo: (selector: string | SimpleElement) => void;
method create
static create: (options: { environment: BootEnvironment; application: InternalOwner; template: TemplateFactory;}) => OutletView;
method destroy
destroy: () => void;
method extend
static extend: (injections: any) => typeof OutletView;
method reopenClass
static reopenClass: (injections: any) => void;
method rerender
rerender: () => void;
method setOutletState
setOutletState: (state: OutletState) => void;
interface BootEnvironment
interface BootEnvironment {}
property hasDOM
hasDOM: boolean;
property isInteractive
isInteractive: boolean;
property options
options: BootOptions;
namespace @ember/-internals/meta
module '@ember/-internals/meta' {}
variable counters
let counters: MetaCounters;
variable meta
const meta: { (obj: object): Meta; _counters?: MetaCounters };
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.
meta Ember
Parameter obj
The object to retrieve meta for
Parameter writable
Pass
false
if you do not intend to modify the meta hash, allowing the method to avoid making an unnecessary copy. {Object} the meta hash for an object
variable UNDEFINED
const UNDEFINED: Symbol;
ember
function peekMeta
peekMeta: (obj: object) => Meta | null;
function setMeta
setMeta: (obj: object, meta: Meta) => void;
class Meta
class Meta {}
method setInitializing
setInitializing: () => void;
interface MetaCounters
interface MetaCounters {}
property addToListenersCalls
addToListenersCalls: number;
property deleteCalls
deleteCalls: number;
property flattenedListenersCalls
flattenedListenersCalls: number;
property listenersFlattened
listenersFlattened: number;
property listenersInherited
listenersInherited: number;
property matchingListenersCalls
matchingListenersCalls: number;
property metaCalls
metaCalls: number;
property metaInstantiated
metaInstantiated: number;
property observerEventsCalls
observerEventsCalls: number;
property parentListenersUsed
parentListenersUsed: number;
property peekCalls
peekCalls: number;
property peekPrototypeWalks
peekPrototypeWalks: number;
property readableLazyChainsCalls
readableLazyChainsCalls: number;
property removeAllListenersCalls
removeAllListenersCalls: number;
property removeFromListenersCalls
removeFromListenersCalls: number;
property reopensAfterFlatten
reopensAfterFlatten: number;
property setCalls
setCalls: number;
property writableLazyChainsCalls
writableLazyChainsCalls: number;
namespace @ember/-internals/meta/lib/meta
module '@ember/-internals/meta/lib/meta' {}
variable counters
let counters: MetaCounters;
variable meta
const meta: { (obj: object): Meta; _counters?: MetaCounters };
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.
meta Ember
Parameter obj
The object to retrieve meta for
Parameter writable
Pass
false
if you do not intend to modify the meta hash, allowing the method to avoid making an unnecessary copy. {Object} the meta hash for an object
variable UNDEFINED
const UNDEFINED: Symbol;
ember
function peekMeta
peekMeta: (obj: object) => Meta | null;
function setMeta
setMeta: (obj: object, meta: Meta) => void;
class Meta
class Meta {}
method setInitializing
setInitializing: () => void;
interface MetaCounters
interface MetaCounters {}
property addToListenersCalls
addToListenersCalls: number;
property deleteCalls
deleteCalls: number;
property flattenedListenersCalls
flattenedListenersCalls: number;
property listenersFlattened
listenersFlattened: number;
property listenersInherited
listenersInherited: number;
property matchingListenersCalls
matchingListenersCalls: number;
property metaCalls
metaCalls: number;
property metaInstantiated
metaInstantiated: number;
property observerEventsCalls
observerEventsCalls: number;
property parentListenersUsed
parentListenersUsed: number;
property peekCalls
peekCalls: number;
property peekPrototypeWalks
peekPrototypeWalks: number;
property readableLazyChainsCalls
readableLazyChainsCalls: number;
property removeAllListenersCalls
removeAllListenersCalls: number;
property removeFromListenersCalls
removeFromListenersCalls: number;
property reopensAfterFlatten
reopensAfterFlatten: number;
property setCalls
setCalls: number;
property writableLazyChainsCalls
writableLazyChainsCalls: number;
namespace @ember/-internals/metal
module '@ember/-internals/metal' {}
variable ASYNC_OBSERVERS
const ASYNC_OBSERVERS: Map<object, Map<string, ActiveObserver>>;
variable cached
const cached: MethodDecorator;
Modifiers
@public
variable DEBUG_INJECTION_FUNCTIONS
let DEBUG_INJECTION_FUNCTIONS: WeakMap<Function, any>;
variable libraries
const libraries: Libraries;
variable NAMESPACES
const NAMESPACES: Namespace[];
variable NAMESPACES_BY_ID
const NAMESPACES_BY_ID: { [name: string]: Namespace };
variable PROPERTY_DID_CHANGE
const PROPERTY_DID_CHANGE: Symbol;
ember
variable PROXY_CONTENT
const PROXY_CONTENT: Symbol;
variable SYNC_OBSERVERS
const SYNC_OBSERVERS: Map<object, Map<string, ActiveObserver>>;
function activateObserver
activateObserver: (target: object, eventName: string, sync?: boolean) => void;
function addArrayObserver
addArrayObserver: <T>( array: EmberArray<T>, target: object | Function | null, opts: ArrayObserverOptions) => ObservedArray<T>;
function addListener
addListener: ( obj: object, eventName: string, target: object | Function | null, method?: Function | PropertyKey, once?: boolean, sync?: boolean) => void;
Add an event listener
addListener @ember/object/events
Parameter obj
Parameter eventName
Parameter target
A target object or a function
Parameter method
A function or the name of a function to be called on
target
Parameter once
A flag whether a function should only be called once
Modifiers
@public
function addNamespace
addNamespace: (namespace: Namespace) => void;
function addObserver
addObserver: ( obj: any, path: string, target: object | Function | null, method?: string | Function, sync?: boolean) => void;
addObserver @ember/object/observers
Parameter obj
Parameter path
Parameter target
Parameter method
Modifiers
@public
function alias
alias: (altKey: string) => AliasDecorator;
function arrayContentDidChange
arrayContentDidChange: <T extends { length: number }>( array: T, startIdx: number, removeAmt: number, addAmt: number, notify?: boolean) => T;
function arrayContentWillChange
arrayContentWillChange: <T extends object>( array: T, startIdx: number, removeAmt: number, addAmt: number) => T;
function autoComputed
autoComputed: ( config_0: ComputedPropertyGetterFunction | ComputedPropertyObj) => ComputedDecorator;
function beginPropertyChanges
beginPropertyChanges: () => void;
beginPropertyChanges
function changeProperties
changeProperties: (callback: () => void) => void;
Make a series of property changes together in an exception-safe way.
```javascript Ember.changeProperties(function() { obj1.set('foo', mayBlowUpWhenSet); obj2.set('bar', baz); }); ```
changeProperties
Parameter callback
function computed
computed: { ( target: object, propertyName: string, descriptor: DecoratorPropertyDescriptor ): DecoratorPropertyDescriptor | void; (...dependentKeys: string[]): ComputedDecorator; (...args: ComputedDecoratorKeysAndConfig): ComputedDecorator; (callback: ComputedPropertyCallback): ComputedDecorator;};
This helper returns a new property descriptor that wraps the passed computed property function. You can use this helper to define properties with native decorator syntax, mixins, or via
defineProperty()
.Example:
```js import { computed, set } from '@ember/object';
class Person { constructor() { this.firstName = 'Betty'; this.lastName = 'Jones'; },
@computed('firstName', 'lastName') get fullName() { return
${this.firstName} ${this.lastName}
; } }let client = new Person();
client.fullName; // 'Betty Jones'
set(client, 'lastName', 'Fuller'); client.fullName; // 'Betty Fuller' ```
Classic Class Example:
```js import EmberObject, { computed } from '@ember/object';
let Person = EmberObject.extend({ init() { this._super(...arguments);
this.firstName = 'Betty'; this.lastName = 'Jones'; },
fullName: computed('firstName', 'lastName', function() { return
${this.get('firstName')} ${this.get('lastName')}
; }) });let client = Person.create();
client.get('fullName'); // 'Betty Jones'
client.set('lastName', 'Fuller'); client.get('fullName'); // 'Betty Fuller' ```
You can also provide a setter, either directly on the class using native class syntax, or by passing a hash with
get
andset
functions.Example:
```js import { computed, set } from '@ember/object';
class Person { constructor() { this.firstName = 'Betty'; this.lastName = 'Jones'; },
@computed('firstName', 'lastName') get fullName() { return
${this.firstName} ${this.lastName}
; }set fullName(value) { let [firstName, lastName] = value.split(/\s+/);
set(this, 'firstName', firstName); set(this, 'lastName', lastName);
return value; } }
let client = new Person();
client.fullName; // 'Betty Jones'
set(client, 'lastName', 'Fuller'); client.fullName; // 'Betty Fuller' ```
Classic Class Example:
```js import EmberObject, { computed } from '@ember/object';
let Person = EmberObject.extend({ init() { this._super(...arguments);
this.firstName = 'Betty'; this.lastName = 'Jones'; },
fullName: computed('firstName', 'lastName', { get(key) { return
${this.get('firstName')} ${this.get('lastName')}
; }, set(key, value) { let [firstName, lastName] = value.split(/\s+/); this.setProperties({ firstName, lastName }); return value; } }) });let client = Person.create(); client.get('firstName'); // 'Betty'
client.set('fullName', 'Carroll Fuller'); client.get('firstName'); // 'Carroll' ```
When passed as an argument, the
set
function should accept two parameters,key
andvalue
. The value returned fromset
will be the new value of the property._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](https://guides.emberjs.com/release/configuring-ember/disabling-prototype-extensions/) enabled._
computed @ember/object
Parameter dependentKeys
Optional dependent keys that trigger this computed property.
Parameter func
The computed property function. {ComputedDecorator} property decorator instance
Modifiers
@public
function defineDecorator
defineDecorator: ( obj: object, keyName: string, desc: ExtendedMethodDecorator, meta: Meta) => ExtendedMethodDecorator;
function defineProperty
defineProperty: ( obj: object, keyName: string, desc?: ExtendedMethodDecorator | PropertyDescriptor | undefined | null, data?: any | undefined | null, _meta?: Meta) => void;
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
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 import { defineProperty, computed } from '@ember/object';
// ES5 compatible mode defineProperty(contact, 'firstName', { writable: true, configurable: false, enumerable: true, value: 'Charles' });
// define a simple property defineProperty(contact, 'lastName', undefined, 'Jolley');
// define a computed property defineProperty(contact, 'fullName', computed('firstName', 'lastName', function() { return this.firstName+' '+this.lastName; })); ```
defineProperty @ember/object
Parameter obj
the object to define this property on. This may be a prototype.
Parameter keyName
the name of the property
Parameter desc
an instance of
Descriptor
(typically a computed property) or an ES5 descriptor. You must provide this ordata
but not both.Parameter data
something other than a descriptor, that will become the explicit value of this property.
Modifiers
@public
function defineValue
defineValue: ( obj: object, keyName: string, value: unknown, wasDescriptor: boolean, enumerable?: boolean) => unknown;
function deprecateProperty
deprecateProperty: ( object: object, deprecatedKey: string, newKey: string, options?: DeprecationOptions) => void;
Used internally to allow changing properties in a backwards compatible way, and print a helpful deprecation warning.
deprecateProperty
Parameter object
The object to add the deprecated property to.
Parameter deprecatedKey
The property to add (and print deprecation warnings upon accessing).
Parameter newKey
The property that will be aliased. 1.7.0
function descriptorForDecorator
descriptorForDecorator: (dec: Function) => ComputedDescriptor | true | undefined;
function descriptorForProperty
descriptorForProperty: ( obj: object, keyName: string, _meta?: Meta | null) => any;
Returns the CP descriptor associated with
obj
andkeyName
, if any.descriptorForProperty
Parameter obj
the object to check
Parameter keyName
the key to check {Descriptor}
function eachProxyArrayDidChange
eachProxyArrayDidChange: ( array: any, idx: number, removedCnt: number, addedCnt: number) => void;
function eachProxyArrayWillChange
eachProxyArrayWillChange: ( array: any, idx: number, removedCnt: number, addedCnt: number) => void;
function endPropertyChanges
endPropertyChanges: () => void;
endPropertyChanges
function expandProperties
expandProperties: ( pattern: string, callback: (expansion: string) => void) => void;
Expands
pattern
, invokingcallback
for each expansion.The only pattern supported is brace-expansion, anything else will be passed once to
callback
directly.Example
```js import { expandProperties } from '@ember/object/computed';
function echo(arg){ console.log(arg); }
expandProperties('foo.bar', echo); //=> 'foo.bar' expandProperties('{foo,bar}', echo); //=> 'foo', 'bar' expandProperties('foo.{bar,baz}', echo); //=> 'foo.bar', 'foo.baz' expandProperties('{foo,bar}.baz', echo); //=> 'foo.baz', 'bar.baz' expandProperties('foo.{bar,baz}.[]', echo) //=> 'foo.bar.[]', 'foo.baz.[]' expandProperties('{foo,bar}.{spam,eggs}', echo) //=> 'foo.spam', 'foo.eggs', 'bar.spam', 'bar.eggs' expandProperties('{foo}.bar.{baz}') //=> 'foo.bar.baz' ```
expandProperties @ember/object/computed
Parameter pattern
The property pattern to expand.
Parameter callback
The callback to invoke. It is invoked once per expansion, and is passed the expansion.
Modifiers
@public
function findNamespace
findNamespace: (name: string) => Namespace | undefined;
function findNamespaces
findNamespaces: () => void;
function flushAsyncObservers
flushAsyncObservers: (_schedule: typeof schedule | false) => void;
function get
get: { <T extends object, K extends keyof T>(obj: T, keyName: K): T[K]; (obj: unknown, keyName: string): unknown;};
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.```javascript import { get } from '@ember/object'; get(obj, "name"); ```
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.get @ember/object
Parameter obj
The object to retrieve from.
Parameter keyName
The property key to retrieve {Object} the property value or
null
.Modifiers
@public
function getCachedValueFor
getCachedValueFor: { <T, K extends keyof T>(obj: T, key: K): T[K] | undefined; (obj: object, key: string): unknown;};
function getProperties
getProperties: { <T, K extends keyof T>(obj: T, list: K[]): Pick<T, K>; <T, K extends keyof T>(obj: T, ...list: K[]): Pick<T, K>; <K extends string>(obj: unknown, list: K[]): Record<K, unknown>; <K extends string>(obj: unknown, ...list: K[]): Record<K, unknown>;};
To get multiple properties at once, call
getProperties
with an object followed by a list of strings or an array:```javascript import { getProperties } from '@ember/object';
getProperties(record, 'firstName', 'lastName', 'zipCode'); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ```
is equivalent to:
```javascript import { getProperties } from '@ember/object';
getProperties(record, ['firstName', 'lastName', 'zipCode']); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ```
getProperties @ember/object
Parameter obj
Parameter list
of keys to get {Object}
Modifiers
@public
function hasListeners
hasListeners: (obj: object, eventName: string) => boolean;
hasListeners @ember/object/events
Parameter obj
Parameter eventName
{Boolean} if
obj
has listeners for eventeventName
Modifiers
@public
function hasUnknownProperty
hasUnknownProperty: (val: unknown) => val is HasUnknownProperty;
function inject
inject: { (type: string, name: string): PropertyDecorator; (type: string): PropertyDecorator; (type: string, args_0: object, args_1: string): void; ( type: string, target: object, propertyName: string, descriptor?: PropertyDescriptor & { initializer?: any } ): PropertyDescriptor & { initializer?: any }; (type: string, ...args: ElementDescriptor | [] | [name: string]): | void | (PropertyDescriptor & { initializer?: any }) | PropertyDecorator;};
Read-only property that returns the result of a container lookup.
InjectedProperty Ember
Parameter type
The container type the property will lookup
Parameter nameOrDesc
(optional) The name the property will lookup, defaults to the property's name
function isClassicDecorator
isClassicDecorator: (dec: unknown) => dec is ExtendedMethodDecorator;
Check whether a value is a decorator
isClassicDecorator
Parameter possibleDesc
the value to check {boolean}
function isComputed
isComputed: (obj: object, key: string) => boolean;
Allows checking if a given property on an object is a computed property. For the most part, this doesn't matter (you would normally just access the property directly and use its value), but for some tooling specific scenarios (e.g. the ember-inspector) it is important to differentiate if a property is a computed property or a "normal" property.
This will work on either a class's prototype or an instance itself.
isComputed @ember/debug
function isElementDescriptor
isElementDescriptor: (args: unknown[]) => args is ElementDescriptor;
function isNamespaceSearchDisabled
isNamespaceSearchDisabled: () => boolean;
function makeComputedDecorator
makeComputedDecorator: ( desc: ComputedDescriptor, DecoratorClass: { prototype: object }) => ExtendedMethodDecorator;
function markObjectAsDirty
markObjectAsDirty: (obj: object, propertyKey: string) => void;
function nativeDescDecorator
nativeDescDecorator: ( propertyDesc: PropertyDescriptor) => () => PropertyDescriptor;
function notifyPropertyChange
notifyPropertyChange: ( obj: object, keyName: string, _meta?: Meta | null, value?: unknown) => void;
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.
notifyPropertyChange @ember/object
Parameter obj
The object with the property that will change
Parameter keyName
The property key (or path) that will change.
Parameter _meta
The objects meta.
Parameter value
The new value to set for the property {void} 3.1.0
Modifiers
@public
function objectAt
objectAt: <T>(array: T[] | EmberArray<T>, index: number) => T | undefined;
function on
on: <T extends AnyFn>(...args: [...eventNames: string[], func: T]) => T;
Define a property as a function that should be executed when a specified event or events are triggered.
``` javascript import EmberObject from '@ember/object'; import { on } from '@ember/object/evented'; import { sendEvent } from '@ember/object/events';
let Job = EmberObject.extend({ logCompleted: on('completed', function() { console.log('Job completed!'); }) });
let job = Job.create();
sendEvent(job, 'completed'); // Logs 'Job completed!' ```
on @ember/object/evented
Parameter eventNames
*
Parameter func
{Function} the listener function, passed as last argument to on(...)
Modifiers
@public
function processAllNamespaces
processAllNamespaces: () => void;
function processNamespace
processNamespace: (namespace: Namespace) => void;
function removeArrayObserver
removeArrayObserver: <T>( array: T[] | EmberArray<T>, target: object | Function | null, opts: ArrayObserverOptions) => ObservedArray<T>;
function removeListener
removeListener: ( obj: object, eventName: string, targetOrFunction: object | Function | null, functionOrName?: string | Function) => void;
Remove an event listener
Arguments should match those passed to
addListener
.removeListener @ember/object/events
Parameter obj
Parameter eventName
Parameter target
A target object or a function
Parameter method
A function or the name of a function to be called on
target
Modifiers
@public
function removeNamespace
removeNamespace: (namespace: Namespace) => void;
function removeObserver
removeObserver: ( obj: any, path: string, target: object | Function | null, method?: string | Function, sync?: boolean) => void;
removeObserver @ember/object/observers
Parameter obj
Parameter path
Parameter target
Parameter method
Modifiers
@public
function replace
replace: <T>( array: T[] | MutableArray<T>, start: number, deleteCount: number, items?: readonly T[]) => void;
function replaceInNativeArray
replaceInNativeArray: <T>( array: T[], start: number, deleteCount: number, items: ReadonlyArray<T>) => void;
function revalidateObservers
revalidateObservers: (target: object) => void;
Primarily used for cases where we are redefining a class, e.g. mixins/reopen being applied later. Revalidates all the observers, resetting their tags.
Parameter target
function sendEvent
sendEvent: ( obj: object, eventName: string, params?: any[], actions?: any[], _meta?: Meta | null) => boolean;
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.
sendEvent @ember/object/events
Parameter obj
Parameter eventName
Parameter params
Optional parameters for each listener. {Boolean} if the event was delivered to one or more actions
Modifiers
@public
function set
set: <T>(obj: object, keyName: string, value: T, tolerant?: boolean) => T;
Sets the value of a property on an object, respecting computed properties and notifying observers and other listeners of the change. If the specified property is not defined on the object and the object implements the
setUnknownProperty
method, then instead of setting the value of the property on the object, itssetUnknownProperty
handler will be invoked with the two parameterskeyName
andvalue
.```javascript import { set } from '@ember/object'; set(obj, "name", value); ```
set @ember/object
Parameter obj
The object to modify.
Parameter keyName
The property key to set
Parameter value
The value to set {Object} the passed value.
Modifiers
@public
function setClassicDecorator
setClassicDecorator: ( dec: ExtendedMethodDecorator, value?: ComputedDescriptor | true) => void;
Set a value as a decorator
setClassicDecorator
Parameter decorator
the value to mark as a decorator
function setNamespaceSearchDisabled
setNamespaceSearchDisabled: (flag: boolean) => void;
function setProperties
setProperties: { <T, K extends keyof T>(obj: T, properties: Pick<T, K>): Pick<T, K>; <T extends Record<string, unknown>>(obj: object, properties: T): T;};
Set a list of properties on an object. These properties are set inside a single
beginPropertyChanges
andendPropertyChanges
batch, so observers will be buffered.```javascript import EmberObject from '@ember/object'; let anObject = EmberObject.create();
anObject.setProperties({ firstName: 'Stanley', lastName: 'Stuart', age: 21 }); ```
setProperties @ember/object
Parameter obj
Parameter properties
properties
Modifiers
@public
function setUnprocessedMixins
setUnprocessedMixins: () => void;
function tagForObject
tagForObject: (obj: unknown | null) => Tag;
function tagForProperty
tagForProperty: ( obj: object, propertyKey: string | symbol, addMandatorySetter?: boolean, meta?: TagMeta) => Tag;
function tracked
tracked: { (propertyDesc: { value: any; initializer: () => any }): ExtendedMethodDecorator; (target: object, key: string): void; ( target: object, key: string, desc: PropertyDescriptor & { initializer?: any } ): PropertyDescriptor & { initializer?: any };};
Parameter dependencies
Optional dependents to be tracked.
Example 1
No dependencies
If you don't pass an argument to
@tracked
, only changes to that property will be tracked:```typescript import Component from '@glimmer/component'; import { tracked } from '@glimmer/tracking';
export default class MyComponent extends Component { remainingApples = 10 } ```
When something changes the component's
remainingApples
property, the rerender will be scheduled.Example 2
Dependents
In the case that you have a computed property that depends other properties, you want to track both so that when one of the dependents change, a rerender is scheduled.
In the following example we have two properties,
eatenApples
, andremainingApples
.```typescript import Component from '@glimmer/component'; import { tracked } from '@glimmer/tracking';
const totalApples = 100;
export default class MyComponent extends Component { eatenApples = 0
get remainingApples() { return totalApples - this.eatenApples; }
increment() { this.eatenApples = this.eatenApples + 1; } } ```
function trySet
trySet: <T>(root: object, path: string, value: T) => T | undefined;
Error-tolerant form of
set
. Will not blow up if any part of the chain isundefined
,null
, or destroyed.This is primarily used when syncing bindings, which may try to update after an object has been destroyed.
```javascript import { trySet } from '@ember/object';
let obj = { name: "Zoey" }; trySet(obj, "contacts.twitter", "@emberjs"); ```
trySet @ember/object
Parameter root
The object to modify.
Parameter path
The property path to set
Parameter value
The value to set
Modifiers
@public
class ComputedDescriptor
abstract class ComputedDescriptor {}
Objects of this type can implement an interface to respond to requests to get and set. The default implementation handles simple properties.
Descriptor
property configurable
configurable: boolean;
property enumerable
enumerable: boolean;
method get
abstract get: (obj: object, keyName: string) => any | null | undefined;
method set
abstract set: ( obj: object, keyName: string, value: any | null | undefined) => any | null | undefined;
method setup
setup: ( _obj: object, keyName: string, _propertyDesc: DecoratorPropertyDescriptor | undefined, meta: Meta) => void;
method teardown
teardown: (_obj: object, keyName: string, meta: Meta) => void;
class ComputedProperty
class ComputedProperty extends ComputedDescriptor {}
@computed
is a decorator that turns a JavaScript getter and setter into a computed property, which is a _cached, trackable value_. By default the getter 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 cleared if the dependencies are modified, and lazily recomputed the next time something asks for it.In the following example we decorate a getter -
fullName
- by callingcomputed
with the property dependencies (firstName
andlastName
) as arguments. ThefullName
getter will be called once (regardless of how many times it is accessed) as long as its dependencies do not change. OncefirstName
orlastName
are updated any future calls tofullName
will incorporate the new values, and any watchers of the value such as templates will be updated:```javascript import { computed, set } from '@ember/object';
class Person { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@computed('firstName', 'lastName') get fullName() { return
${this.firstName} ${this.lastName}
; } });let tom = new Person('Tom', 'Dale');
tom.fullName; // 'Tom Dale' ```
You can also provide a setter, which will be used when updating the computed property. Ember's
set
function must be used to update the property since it will also notify observers of the property:```javascript import { computed, set } from '@ember/object';
class Person { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@computed('firstName', 'lastName') get fullName() { return
${this.firstName} ${this.lastName}
; }set fullName(value) { let [firstName, lastName] = value.split(' ');
set(this, 'firstName', firstName); set(this, 'lastName', lastName); } });
let person = new Person();
set(person, 'fullName', 'Peter Wagenet'); person.firstName; // 'Peter' person.lastName; // 'Wagenet' ```
You can also pass a getter function or object with
get
andset
functions as the last argument to the computed decorator. This allows you to define computed property _macros_:```js import { computed } from '@ember/object';
function join(...keys) { return computed(...keys, function() { return keys.map(key => this[key]).join(' '); }); }
class Person { @join('firstName', 'lastName') fullName; } ```
Note that when defined this way, getters and setters receive the _key_ of the property they are decorating as the first argument. Setters receive the value they are setting to as the second argument instead. Additionally, setters must _return_ the value that should be cached:
```javascript import { computed, set } from '@ember/object';
function fullNameMacro(firstNameKey, lastNameKey) { return computed(firstNameKey, lastNameKey, { get() { return
${this[firstNameKey]} ${this[lastNameKey]}
; }set(key, value) { let [firstName, lastName] = value.split(' ');
set(this, firstNameKey, firstName); set(this, lastNameKey, lastName);
return value; } }); }
class Person { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@fullNameMacro('firstName', 'lastName') fullName; });
let person = new Person();
set(person, 'fullName', 'Peter Wagenet'); person.firstName; // 'Peter' person.lastName; // 'Wagenet' ```
Computed properties can also be used in classic classes. To do this, we provide the getter and setter as the last argument like we would for a macro, and we assign it to a property on the class definition. This is an _anonymous_ computed macro:
```javascript import EmberObject, { computed, set } from '@ember/object';
let Person = EmberObject.extend({ // these will be supplied by
create
firstName: null, lastName: null,fullName: computed('firstName', 'lastName', { get() { return
${this.firstName} ${this.lastName}
; }set(key, value) { let [firstName, lastName] = value.split(' ');
set(this, 'firstName', firstName); set(this, 'lastName', lastName);
return value; } }) });
let tom = Person.create({ firstName: 'Tom', lastName: 'Dale' });
tom.get('fullName') // 'Tom Dale' ```
You can overwrite computed property without setters with a normal property (no longer computed) that won't change if dependencies change. You can also mark computed property as
.readOnly()
and block all attempts to set it.```javascript import { computed, set } from '@ember/object';
class Person { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@computed('firstName', 'lastName').readOnly() get fullName() { return
${this.firstName} ${this.lastName}
; } });let person = new Person(); person.set('fullName', 'Peter Wagenet'); // Uncaught Error: Cannot set read-only property "fullName" on object: <(...):emberXXX> ```
Additional resources: - [Decorators RFC](https://github.com/emberjs/rfcs/blob/master/text/0408-decorators.md) - [New CP syntax RFC](https://github.com/emberjs/rfcs/blob/master/text/0011-improved-cp-syntax.md) - [New computed syntax explained in "Ember 1.12 released" ](https://emberjs.com/blog/2015/05/13/ember-1-12-released.html#toc_new-computed-syntax)
ComputedProperty
Modifiers
@public
constructor
constructor(args: (string | ComputedPropertyCallback)[]);
method get
get: (obj: object, keyName: string) => unknown;
method set
set: (obj: object, keyName: string, value: unknown) => unknown;
method setup
setup: ( obj: object, keyName: string, propertyDesc: DecoratorPropertyDescriptor, meta: Meta) => void;
method teardown
teardown: (obj: object, keyName: string, meta: Meta) => void;
class Libraries
class Libraries {}
Helper class that allows you to register your library with Ember.
Singleton created at
Ember.libraries
.Libraries
constructor
constructor();
property isRegistered
isRegistered?: (name: string) => boolean;
property logVersions
logVersions?: () => void;
method deRegister
deRegister: (name: string) => void;
method register
register: (name: string, version: string, isCoreLibrary?: boolean) => void;
method registerCoreLibrary
registerCoreLibrary: (name: string, version: string) => void;
class TrackedDescriptor
class TrackedDescriptor {}
constructor
constructor(_get: () => unknown, _set: (value: unknown) => void);
method get
get: (obj: object) => unknown;
method set
set: (obj: object, _key: string, value: unknown) => void;
interface HasUnknownProperty
interface HasUnknownProperty {}
property unknownProperty
unknownProperty: (keyName: string) => any;
interface PropertyDidChange
interface PropertyDidChange {}
property [PROPERTY_DID_CHANGE]
[PROPERTY_DID_CHANGE]: (keyName: string, value?: unknown) => void;
type ComputedDecorator
type ComputedDecorator = ExtendedMethodDecorator & PropertyDecorator & ComputedDecoratorImpl;
type ComputedPropertyCallback
type ComputedPropertyCallback = ComputedPropertyGetterFunction | ComputedPropertyObj;
type ComputedPropertyGetter
type ComputedPropertyGetter = | ComputedPropertyGetterFunction | ComputedPropertyGetterObj;
type ComputedPropertyObj
type ComputedPropertyObj = | ComputedPropertyGetterObj | ComputedPropertySetterObj | (ComputedPropertyGetterObj & ComputedPropertySetterObj);
type ComputedPropertySetter
type ComputedPropertySetter = | ComputedPropertySetterFunction | ComputedPropertySetterObj;
type DecoratorPropertyDescriptor
type DecoratorPropertyDescriptor = | (PropertyDescriptor & { initializer?: any; }) | undefined;
type ElementDescriptor
type ElementDescriptor = [ target: object, propertyName: string, descriptor?: DecoratorPropertyDescriptor];
type ExtendedMethodDecorator
type ExtendedMethodDecorator = ( target: object, key: string, desc: DecoratorPropertyDescriptor, maybeMeta?: Meta, isClassicDecorator?: boolean) => DecoratorPropertyDescriptor;
namespace @ember/-internals/metal/lib/alias
module '@ember/-internals/metal/lib/alias' {}
function alias
alias: (altKey: string) => AliasDecorator;
class AliasedProperty
class AliasedProperty extends ComputedDescriptor {}
constructor
constructor(altKey: string);
property altKey
readonly altKey: string;
method get
get: (obj: object, keyName: string) => any;
method oneWay
oneWay: () => void;
method readOnly
readOnly: () => void;
method set
set: (obj: object, _keyName: string, value: any) => any;
method setup
setup: ( obj: object, keyName: string, propertyDesc: PropertyDescriptor, meta: Meta) => void;
type AliasDecorator
type AliasDecorator = ExtendedMethodDecorator & PropertyDecorator & AliasDecoratorImpl;
namespace @ember/-internals/metal/lib/array
module '@ember/-internals/metal/lib/array' {}
function addArrayObserver
addArrayObserver: <T>( array: EmberArray<T>, target: object | Function | null, opts: ArrayObserverOptions) => ObservedArray<T>;
function objectAt
objectAt: <T>(array: T[] | EmberArray<T>, index: number) => T | undefined;
function removeArrayObserver
removeArrayObserver: <T>( array: T[] | EmberArray<T>, target: object | Function | null, opts: ArrayObserverOptions) => ObservedArray<T>;
function replace
replace: <T>( array: T[] | MutableArray<T>, start: number, deleteCount: number, items?: readonly T[]) => void;
function replaceInNativeArray
replaceInNativeArray: <T>( array: T[], start: number, deleteCount: number, items: ReadonlyArray<T>) => void;
namespace @ember/-internals/metal/lib/array_events
module '@ember/-internals/metal/lib/array_events' {}
function arrayContentDidChange
arrayContentDidChange: <T extends { length: number }>( array: T, startIdx: number, removeAmt: number, addAmt: number, notify?: boolean) => T;
function arrayContentWillChange
arrayContentWillChange: <T extends object>( array: T, startIdx: number, removeAmt: number, addAmt: number) => T;
namespace @ember/-internals/metal/lib/cache
module '@ember/-internals/metal/lib/cache' {}
namespace @ember/-internals/metal/lib/cached
module '@ember/-internals/metal/lib/cached' {}
variable cached
const cached: MethodDecorator;
Modifiers
@public
namespace @ember/-internals/metal/lib/chain-tags
module '@ember/-internals/metal/lib/chain-tags' {}
variable CHAIN_PASS_THROUGH
const CHAIN_PASS_THROUGH: WeakSet<object>;
function finishLazyChains
finishLazyChains: (meta: Meta, key: string, value: any) => void;
function getChainTagsForKey
getChainTagsForKey: ( obj: object, key: string, tagMeta: TagMeta, meta: Meta | null) => Tag;
function getChainTagsForKeys
getChainTagsForKeys: ( obj: object, keys: string[], tagMeta: TagMeta, meta: Meta | null) => Tag;
namespace @ember/-internals/metal/lib/change_event
module '@ember/-internals/metal/lib/change_event' {}
function changeEvent
changeEvent: (keyName: string) => string;
namespace @ember/-internals/metal/lib/computed
module '@ember/-internals/metal/lib/computed' {}
function autoComputed
autoComputed: ( config_0: ComputedPropertyGetterFunction | ComputedPropertyObj) => ComputedDecorator;
function computed
computed: { ( target: object, propertyName: string, descriptor: DecoratorPropertyDescriptor ): DecoratorPropertyDescriptor | void; (...dependentKeys: string[]): ComputedDecorator; (...args: ComputedDecoratorKeysAndConfig): ComputedDecorator; (callback: ComputedPropertyCallback): ComputedDecorator;};
This helper returns a new property descriptor that wraps the passed computed property function. You can use this helper to define properties with native decorator syntax, mixins, or via
defineProperty()
.Example:
```js import { computed, set } from '@ember/object';
class Person { constructor() { this.firstName = 'Betty'; this.lastName = 'Jones'; },
@computed('firstName', 'lastName') get fullName() { return
${this.firstName} ${this.lastName}
; } }let client = new Person();
client.fullName; // 'Betty Jones'
set(client, 'lastName', 'Fuller'); client.fullName; // 'Betty Fuller' ```
Classic Class Example:
```js import EmberObject, { computed } from '@ember/object';
let Person = EmberObject.extend({ init() { this._super(...arguments);
this.firstName = 'Betty'; this.lastName = 'Jones'; },
fullName: computed('firstName', 'lastName', function() { return
${this.get('firstName')} ${this.get('lastName')}
; }) });let client = Person.create();
client.get('fullName'); // 'Betty Jones'
client.set('lastName', 'Fuller'); client.get('fullName'); // 'Betty Fuller' ```
You can also provide a setter, either directly on the class using native class syntax, or by passing a hash with
get
andset
functions.Example:
```js import { computed, set } from '@ember/object';
class Person { constructor() { this.firstName = 'Betty'; this.lastName = 'Jones'; },
@computed('firstName', 'lastName') get fullName() { return
${this.firstName} ${this.lastName}
; }set fullName(value) { let [firstName, lastName] = value.split(/\s+/);
set(this, 'firstName', firstName); set(this, 'lastName', lastName);
return value; } }
let client = new Person();
client.fullName; // 'Betty Jones'
set(client, 'lastName', 'Fuller'); client.fullName; // 'Betty Fuller' ```
Classic Class Example:
```js import EmberObject, { computed } from '@ember/object';
let Person = EmberObject.extend({ init() { this._super(...arguments);
this.firstName = 'Betty'; this.lastName = 'Jones'; },
fullName: computed('firstName', 'lastName', { get(key) { return
${this.get('firstName')} ${this.get('lastName')}
; }, set(key, value) { let [firstName, lastName] = value.split(/\s+/); this.setProperties({ firstName, lastName }); return value; } }) });let client = Person.create(); client.get('firstName'); // 'Betty'
client.set('fullName', 'Carroll Fuller'); client.get('firstName'); // 'Carroll' ```
When passed as an argument, the
set
function should accept two parameters,key
andvalue
. The value returned fromset
will be the new value of the property._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](https://guides.emberjs.com/release/configuring-ember/disabling-prototype-extensions/) enabled._
computed @ember/object
Parameter dependentKeys
Optional dependent keys that trigger this computed property.
Parameter func
The computed property function. {ComputedDecorator} property decorator instance
Modifiers
@public
function isComputed
isComputed: (obj: object, key: string) => boolean;
Allows checking if a given property on an object is a computed property. For the most part, this doesn't matter (you would normally just access the property directly and use its value), but for some tooling specific scenarios (e.g. the ember-inspector) it is important to differentiate if a property is a computed property or a "normal" property.
This will work on either a class's prototype or an instance itself.
isComputed @ember/debug
class ComputedProperty
class ComputedProperty extends ComputedDescriptor {}
@computed
is a decorator that turns a JavaScript getter and setter into a computed property, which is a _cached, trackable value_. By default the getter 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 cleared if the dependencies are modified, and lazily recomputed the next time something asks for it.In the following example we decorate a getter -
fullName
- by callingcomputed
with the property dependencies (firstName
andlastName
) as arguments. ThefullName
getter will be called once (regardless of how many times it is accessed) as long as its dependencies do not change. OncefirstName
orlastName
are updated any future calls tofullName
will incorporate the new values, and any watchers of the value such as templates will be updated:```javascript import { computed, set } from '@ember/object';
class Person { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@computed('firstName', 'lastName') get fullName() { return
${this.firstName} ${this.lastName}
; } });let tom = new Person('Tom', 'Dale');
tom.fullName; // 'Tom Dale' ```
You can also provide a setter, which will be used when updating the computed property. Ember's
set
function must be used to update the property since it will also notify observers of the property:```javascript import { computed, set } from '@ember/object';
class Person { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@computed('firstName', 'lastName') get fullName() { return
${this.firstName} ${this.lastName}
; }set fullName(value) { let [firstName, lastName] = value.split(' ');
set(this, 'firstName', firstName); set(this, 'lastName', lastName); } });
let person = new Person();
set(person, 'fullName', 'Peter Wagenet'); person.firstName; // 'Peter' person.lastName; // 'Wagenet' ```
You can also pass a getter function or object with
get
andset
functions as the last argument to the computed decorator. This allows you to define computed property _macros_:```js import { computed } from '@ember/object';
function join(...keys) { return computed(...keys, function() { return keys.map(key => this[key]).join(' '); }); }
class Person { @join('firstName', 'lastName') fullName; } ```
Note that when defined this way, getters and setters receive the _key_ of the property they are decorating as the first argument. Setters receive the value they are setting to as the second argument instead. Additionally, setters must _return_ the value that should be cached:
```javascript import { computed, set } from '@ember/object';
function fullNameMacro(firstNameKey, lastNameKey) { return computed(firstNameKey, lastNameKey, { get() { return
${this[firstNameKey]} ${this[lastNameKey]}
; }set(key, value) { let [firstName, lastName] = value.split(' ');
set(this, firstNameKey, firstName); set(this, lastNameKey, lastName);
return value; } }); }
class Person { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@fullNameMacro('firstName', 'lastName') fullName; });
let person = new Person();
set(person, 'fullName', 'Peter Wagenet'); person.firstName; // 'Peter' person.lastName; // 'Wagenet' ```
Computed properties can also be used in classic classes. To do this, we provide the getter and setter as the last argument like we would for a macro, and we assign it to a property on the class definition. This is an _anonymous_ computed macro:
```javascript import EmberObject, { computed, set } from '@ember/object';
let Person = EmberObject.extend({ // these will be supplied by
create
firstName: null, lastName: null,fullName: computed('firstName', 'lastName', { get() { return
${this.firstName} ${this.lastName}
; }set(key, value) { let [firstName, lastName] = value.split(' ');
set(this, 'firstName', firstName); set(this, 'lastName', lastName);
return value; } }) });
let tom = Person.create({ firstName: 'Tom', lastName: 'Dale' });
tom.get('fullName') // 'Tom Dale' ```
You can overwrite computed property without setters with a normal property (no longer computed) that won't change if dependencies change. You can also mark computed property as
.readOnly()
and block all attempts to set it.```javascript import { computed, set } from '@ember/object';
class Person { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@computed('firstName', 'lastName').readOnly() get fullName() { return
${this.firstName} ${this.lastName}
; } });let person = new Person(); person.set('fullName', 'Peter Wagenet'); // Uncaught Error: Cannot set read-only property "fullName" on object: <(...):emberXXX> ```
Additional resources: - [Decorators RFC](https://github.com/emberjs/rfcs/blob/master/text/0408-decorators.md) - [New CP syntax RFC](https://github.com/emberjs/rfcs/blob/master/text/0011-improved-cp-syntax.md) - [New computed syntax explained in "Ember 1.12 released" ](https://emberjs.com/blog/2015/05/13/ember-1-12-released.html#toc_new-computed-syntax)
ComputedProperty
Modifiers
@public
constructor
constructor(args: (string | ComputedPropertyCallback)[]);
method get
get: (obj: object, keyName: string) => unknown;
method set
set: (obj: object, keyName: string, value: unknown) => unknown;
method setup
setup: ( obj: object, keyName: string, propertyDesc: DecoratorPropertyDescriptor, meta: Meta) => void;
method teardown
teardown: (obj: object, keyName: string, meta: Meta) => void;
interface ComputedPropertyGetterObj
interface ComputedPropertyGetterObj {}
method get
get: (this: any, key: string) => unknown;
interface ComputedPropertySetterObj
interface ComputedPropertySetterObj {}
method set
set: (this: any, key: string, value: unknown) => unknown;
type ComputedDecorator
type ComputedDecorator = ExtendedMethodDecorator & PropertyDecorator & ComputedDecoratorImpl;
type ComputedPropertyCallback
type ComputedPropertyCallback = ComputedPropertyGetterFunction | ComputedPropertyObj;
type ComputedPropertyGetter
type ComputedPropertyGetter = | ComputedPropertyGetterFunction | ComputedPropertyGetterObj;
type ComputedPropertyGetterFunction
type ComputedPropertyGetterFunction = (this: any, key: string) => unknown;
type ComputedPropertyObj
type ComputedPropertyObj = | ComputedPropertyGetterObj | ComputedPropertySetterObj | (ComputedPropertyGetterObj & ComputedPropertySetterObj);
type ComputedPropertySetter
type ComputedPropertySetter = | ComputedPropertySetterFunction | ComputedPropertySetterObj;
type ComputedPropertySetterFunction
type ComputedPropertySetterFunction = ( this: any, key: string, newVal: unknown, oldVal: unknown) => unknown;
namespace @ember/-internals/metal/lib/computed_cache
module '@ember/-internals/metal/lib/computed_cache' {}
function getCachedValueFor
getCachedValueFor: { <T, K extends keyof T>(obj: T, key: K): T[K] | undefined; (obj: object, key: string): unknown;};
namespace @ember/-internals/metal/lib/decorator
module '@ember/-internals/metal/lib/decorator' {}
variable COMPUTED_GETTERS
let COMPUTED_GETTERS: WeakSet<() => unknown>;
variable COMPUTED_SETTERS
const COMPUTED_SETTERS: WeakSet<object>;
function descriptorForDecorator
descriptorForDecorator: (dec: Function) => ComputedDescriptor | true | undefined;
function descriptorForProperty
descriptorForProperty: ( obj: object, keyName: string, _meta?: Meta | null) => any;
Returns the CP descriptor associated with
obj
andkeyName
, if any.descriptorForProperty
Parameter obj
the object to check
Parameter keyName
the key to check {Descriptor}
function isClassicDecorator
isClassicDecorator: (dec: unknown) => dec is ExtendedMethodDecorator;
Check whether a value is a decorator
isClassicDecorator
Parameter possibleDesc
the value to check {boolean}
function isElementDescriptor
isElementDescriptor: (args: unknown[]) => args is ElementDescriptor;
function makeComputedDecorator
makeComputedDecorator: ( desc: ComputedDescriptor, DecoratorClass: { prototype: object }) => ExtendedMethodDecorator;
function nativeDescDecorator
nativeDescDecorator: ( propertyDesc: PropertyDescriptor) => () => PropertyDescriptor;
function setClassicDecorator
setClassicDecorator: ( dec: ExtendedMethodDecorator, value?: ComputedDescriptor | true) => void;
Set a value as a decorator
setClassicDecorator
Parameter decorator
the value to mark as a decorator
class ComputedDescriptor
abstract class ComputedDescriptor {}
Objects of this type can implement an interface to respond to requests to get and set. The default implementation handles simple properties.
Descriptor
property configurable
configurable: boolean;
property enumerable
enumerable: boolean;
method get
abstract get: (obj: object, keyName: string) => any | null | undefined;
method set
abstract set: ( obj: object, keyName: string, value: any | null | undefined) => any | null | undefined;
method setup
setup: ( _obj: object, keyName: string, _propertyDesc: DecoratorPropertyDescriptor | undefined, meta: Meta) => void;
method teardown
teardown: (_obj: object, keyName: string, meta: Meta) => void;
type DecoratorPropertyDescriptor
type DecoratorPropertyDescriptor = | (PropertyDescriptor & { initializer?: any; }) | undefined;
type ElementDescriptor
type ElementDescriptor = [ target: object, propertyName: string, descriptor?: DecoratorPropertyDescriptor];
type ExtendedMethodDecorator
type ExtendedMethodDecorator = ( target: object, key: string, desc: DecoratorPropertyDescriptor, maybeMeta?: Meta, isClassicDecorator?: boolean) => DecoratorPropertyDescriptor;
namespace @ember/-internals/metal/lib/dependent_keys
module '@ember/-internals/metal/lib/dependent_keys' {}
namespace @ember/-internals/metal/lib/deprecate_property
module '@ember/-internals/metal/lib/deprecate_property' {}
function deprecateProperty
deprecateProperty: ( object: object, deprecatedKey: string, newKey: string, options?: DeprecationOptions) => void;
Used internally to allow changing properties in a backwards compatible way, and print a helpful deprecation warning.
deprecateProperty
Parameter object
The object to add the deprecated property to.
Parameter deprecatedKey
The property to add (and print deprecation warnings upon accessing).
Parameter newKey
The property that will be aliased. 1.7.0
namespace @ember/-internals/metal/lib/each_proxy_events
module '@ember/-internals/metal/lib/each_proxy_events' {}
variable EACH_PROXIES
const EACH_PROXIES: WeakMap<object, any>;
function eachProxyArrayDidChange
eachProxyArrayDidChange: ( array: any, idx: number, removedCnt: number, addedCnt: number) => void;
function eachProxyArrayWillChange
eachProxyArrayWillChange: ( array: any, idx: number, removedCnt: number, addedCnt: number) => void;
namespace @ember/-internals/metal/lib/events
module '@ember/-internals/metal/lib/events' {}
function addListener
addListener: ( obj: object, eventName: string, target: object | Function | null, method?: Function | PropertyKey, once?: boolean, sync?: boolean) => void;
Add an event listener
addListener @ember/object/events
Parameter obj
Parameter eventName
Parameter target
A target object or a function
Parameter method
A function or the name of a function to be called on
target
Parameter once
A flag whether a function should only be called once
Modifiers
@public
function hasListeners
hasListeners: (obj: object, eventName: string) => boolean;
hasListeners @ember/object/events
Parameter obj
Parameter eventName
{Boolean} if
obj
has listeners for eventeventName
Modifiers
@public
function on
on: <T extends AnyFn>(...args: [...eventNames: string[], func: T]) => T;
Define a property as a function that should be executed when a specified event or events are triggered.
``` javascript import EmberObject from '@ember/object'; import { on } from '@ember/object/evented'; import { sendEvent } from '@ember/object/events';
let Job = EmberObject.extend({ logCompleted: on('completed', function() { console.log('Job completed!'); }) });
let job = Job.create();
sendEvent(job, 'completed'); // Logs 'Job completed!' ```
on @ember/object/evented
Parameter eventNames
*
Parameter func
{Function} the listener function, passed as last argument to on(...)
Modifiers
@public
function removeListener
removeListener: ( obj: object, eventName: string, targetOrFunction: object | Function | null, functionOrName?: string | Function) => void;
Remove an event listener
Arguments should match those passed to
addListener
.removeListener @ember/object/events
Parameter obj
Parameter eventName
Parameter target
A target object or a function
Parameter method
A function or the name of a function to be called on
target
Modifiers
@public
function sendEvent
sendEvent: ( obj: object, eventName: string, params?: any[], actions?: any[], _meta?: Meta | null) => boolean;
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.
sendEvent @ember/object/events
Parameter obj
Parameter eventName
Parameter params
Optional parameters for each listener. {Boolean} if the event was delivered to one or more actions
Modifiers
@public
namespace @ember/-internals/metal/lib/expand_properties
module '@ember/-internals/metal/lib/expand_properties' {}
function expandProperties
expandProperties: ( pattern: string, callback: (expansion: string) => void) => void;
Expands
pattern
, invokingcallback
for each expansion.The only pattern supported is brace-expansion, anything else will be passed once to
callback
directly.Example
```js import { expandProperties } from '@ember/object/computed';
function echo(arg){ console.log(arg); }
expandProperties('foo.bar', echo); //=> 'foo.bar' expandProperties('{foo,bar}', echo); //=> 'foo', 'bar' expandProperties('foo.{bar,baz}', echo); //=> 'foo.bar', 'foo.baz' expandProperties('{foo,bar}.baz', echo); //=> 'foo.baz', 'bar.baz' expandProperties('foo.{bar,baz}.[]', echo) //=> 'foo.bar.[]', 'foo.baz.[]' expandProperties('{foo,bar}.{spam,eggs}', echo) //=> 'foo.spam', 'foo.eggs', 'bar.spam', 'bar.eggs' expandProperties('{foo}.bar.{baz}') //=> 'foo.bar.baz' ```
expandProperties @ember/object/computed
Parameter pattern
The property pattern to expand.
Parameter callback
The callback to invoke. It is invoked once per expansion, and is passed the expansion.
Modifiers
@public
namespace @ember/-internals/metal/lib/get_properties
module '@ember/-internals/metal/lib/get_properties' {}
function getProperties
getProperties: { <T, K extends keyof T>(obj: T, list: K[]): Pick<T, K>; <T, K extends keyof T>(obj: T, ...list: K[]): Pick<T, K>; <K extends string>(obj: unknown, list: K[]): Record<K, unknown>; <K extends string>(obj: unknown, ...list: K[]): Record<K, unknown>;};
To get multiple properties at once, call
getProperties
with an object followed by a list of strings or an array:```javascript import { getProperties } from '@ember/object';
getProperties(record, 'firstName', 'lastName', 'zipCode'); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ```
is equivalent to:
```javascript import { getProperties } from '@ember/object';
getProperties(record, ['firstName', 'lastName', 'zipCode']); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ```
getProperties @ember/object
Parameter obj
Parameter list
of keys to get {Object}
Modifiers
@public
namespace @ember/-internals/metal/lib/injected_property
module '@ember/-internals/metal/lib/injected_property' {}
variable DEBUG_INJECTION_FUNCTIONS
let DEBUG_INJECTION_FUNCTIONS: WeakMap<Function, any>;
function inject
inject: { (type: string, name: string): PropertyDecorator; (type: string): PropertyDecorator; (type: string, args_0: object, args_1: string): void; ( type: string, target: object, propertyName: string, descriptor?: PropertyDescriptor & { initializer?: any } ): PropertyDescriptor & { initializer?: any }; (type: string, ...args: ElementDescriptor | [] | [name: string]): | void | (PropertyDescriptor & { initializer?: any }) | PropertyDecorator;};
Read-only property that returns the result of a container lookup.
InjectedProperty Ember
Parameter type
The container type the property will lookup
Parameter nameOrDesc
(optional) The name the property will lookup, defaults to the property's name
namespace @ember/-internals/metal/lib/libraries
module '@ember/-internals/metal/lib/libraries' {}
variable LIBRARIES
const LIBRARIES: Libraries;
class Libraries
class Libraries {}
Helper class that allows you to register your library with Ember.
Singleton created at
Ember.libraries
.Libraries
constructor
constructor();
property isRegistered
isRegistered?: (name: string) => boolean;
property logVersions
logVersions?: () => void;
method deRegister
deRegister: (name: string) => void;
method register
register: (name: string, version: string, isCoreLibrary?: boolean) => void;
method registerCoreLibrary
registerCoreLibrary: (name: string, version: string) => void;
namespace @ember/-internals/metal/lib/namespace_search
module '@ember/-internals/metal/lib/namespace_search' {}
variable NAMESPACES
const NAMESPACES: Namespace[];
variable NAMESPACES_BY_ID
const NAMESPACES_BY_ID: { [name: string]: Namespace };
function addNamespace
addNamespace: (namespace: Namespace) => void;
function findNamespace
findNamespace: (name: string) => Namespace | undefined;
function findNamespaces
findNamespaces: () => void;
function isSearchDisabled
isSearchDisabled: () => boolean;
function processAllNamespaces
processAllNamespaces: () => void;
function processNamespace
processNamespace: (namespace: Namespace) => void;
function removeNamespace
removeNamespace: (namespace: Namespace) => void;
function setSearchDisabled
setSearchDisabled: (flag: boolean) => void;
function setUnprocessedMixins
setUnprocessedMixins: () => void;
interface Namespace
interface Namespace {}
property isNamespace
isNamespace: true;
method destroy
destroy: () => void;
namespace @ember/-internals/metal/lib/object-at
module '@ember/-internals/metal/lib/object-at' {}
function objectAt
objectAt: <T>(array: T[] | EmberArray<T>, index: number) => T | undefined;
namespace @ember/-internals/metal/lib/observer
module '@ember/-internals/metal/lib/observer' {}
variable ASYNC_OBSERVERS
const ASYNC_OBSERVERS: Map<object, Map<string, ActiveObserver>>;
variable SYNC_OBSERVERS
const SYNC_OBSERVERS: Map<object, Map<string, ActiveObserver>>;
function activateObserver
activateObserver: (target: object, eventName: string, sync?: boolean) => void;
function addObserver
addObserver: ( obj: any, path: string, target: object | Function | null, method?: string | Function, sync?: boolean) => void;
addObserver @ember/object/observers
Parameter obj
Parameter path
Parameter target
Parameter method
Modifiers
@public
function deactivateObserver
deactivateObserver: (target: object, eventName: string, sync?: boolean) => void;
function destroyObservers
destroyObservers: (target: object) => void;
function flushAsyncObservers
flushAsyncObservers: (_schedule: typeof schedule | false) => void;
function flushSyncObservers
flushSyncObservers: () => void;
function removeObserver
removeObserver: ( obj: any, path: string, target: object | Function | null, method?: string | Function, sync?: boolean) => void;
removeObserver @ember/object/observers
Parameter obj
Parameter path
Parameter target
Parameter method
Modifiers
@public
function resumeObserverDeactivation
resumeObserverDeactivation: () => void;
function revalidateObservers
revalidateObservers: (target: object) => void;
Primarily used for cases where we are redefining a class, e.g. mixins/reopen being applied later. Revalidates all the observers, resetting their tags.
Parameter target
function setObserverSuspended
setObserverSuspended: ( target: object, property: string, suspended: boolean) => void;
function suspendedObserverDeactivation
suspendedObserverDeactivation: () => void;
namespace @ember/-internals/metal/lib/path_cache
module '@ember/-internals/metal/lib/path_cache' {}
function isPath
isPath: (path: unknown) => boolean;
namespace @ember/-internals/metal/lib/properties
module '@ember/-internals/metal/lib/properties' {}
function defineDecorator
defineDecorator: ( obj: object, keyName: string, desc: ExtendedMethodDecorator, meta: Meta) => ExtendedMethodDecorator;
function defineProperty
defineProperty: ( obj: object, keyName: string, desc?: ExtendedMethodDecorator | PropertyDescriptor | undefined | null, data?: any | undefined | null, _meta?: Meta) => void;
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
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 import { defineProperty, computed } from '@ember/object';
// ES5 compatible mode defineProperty(contact, 'firstName', { writable: true, configurable: false, enumerable: true, value: 'Charles' });
// define a simple property defineProperty(contact, 'lastName', undefined, 'Jolley');
// define a computed property defineProperty(contact, 'fullName', computed('firstName', 'lastName', function() { return this.firstName+' '+this.lastName; })); ```
defineProperty @ember/object
Parameter obj
the object to define this property on. This may be a prototype.
Parameter keyName
the name of the property
Parameter desc
an instance of
Descriptor
(typically a computed property) or an ES5 descriptor. You must provide this ordata
but not both.Parameter data
something other than a descriptor, that will become the explicit value of this property.
Modifiers
@public
function defineValue
defineValue: ( obj: object, keyName: string, value: unknown, wasDescriptor: boolean, enumerable?: boolean) => unknown;
namespace @ember/-internals/metal/lib/property_events
module '@ember/-internals/metal/lib/property_events' {}
variable PROPERTY_DID_CHANGE
const PROPERTY_DID_CHANGE: Symbol;
ember
function beginPropertyChanges
beginPropertyChanges: () => void;
beginPropertyChanges
function changeProperties
changeProperties: (callback: () => void) => void;
Make a series of property changes together in an exception-safe way.
```javascript Ember.changeProperties(function() { obj1.set('foo', mayBlowUpWhenSet); obj2.set('bar', baz); }); ```
changeProperties
Parameter callback
function endPropertyChanges
endPropertyChanges: () => void;
endPropertyChanges
function hasPropertyDidChange
hasPropertyDidChange: (obj: unknown) => obj is PropertyDidChange;
function notifyPropertyChange
notifyPropertyChange: ( obj: object, keyName: string, _meta?: Meta | null, value?: unknown) => void;
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.
notifyPropertyChange @ember/object
Parameter obj
The object with the property that will change
Parameter keyName
The property key (or path) that will change.
Parameter _meta
The objects meta.
Parameter value
The new value to set for the property {void} 3.1.0
Modifiers
@public
interface PropertyDidChange
interface PropertyDidChange {}
property [PROPERTY_DID_CHANGE]
[PROPERTY_DID_CHANGE]: (keyName: string, value?: unknown) => void;
namespace @ember/-internals/metal/lib/property_get
module '@ember/-internals/metal/lib/property_get' {}
variable PROXY_CONTENT
const PROXY_CONTENT: Symbol;
function get
get: { <T extends object, K extends keyof T>(obj: T, keyName: K): T[K]; (obj: unknown, keyName: string): unknown;};
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.```javascript import { get } from '@ember/object'; get(obj, "name"); ```
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.get @ember/object
Parameter obj
The object to retrieve from.
Parameter keyName
The property key to retrieve {Object} the property value or
null
.Modifiers
@public
function getPossibleMandatoryProxyValue
getPossibleMandatoryProxyValue: (obj: object, keyName: string) => any;
function hasUnknownProperty
hasUnknownProperty: (val: unknown) => val is HasUnknownProperty;
interface HasUnknownProperty
interface HasUnknownProperty {}
property unknownProperty
unknownProperty: (keyName: string) => any;
namespace @ember/-internals/metal/lib/property_set
module '@ember/-internals/metal/lib/property_set' {}
function set
set: <T>(obj: object, keyName: string, value: T, tolerant?: boolean) => T;
Sets the value of a property on an object, respecting computed properties and notifying observers and other listeners of the change. If the specified property is not defined on the object and the object implements the
setUnknownProperty
method, then instead of setting the value of the property on the object, itssetUnknownProperty
handler will be invoked with the two parameterskeyName
andvalue
.```javascript import { set } from '@ember/object'; set(obj, "name", value); ```
set @ember/object
Parameter obj
The object to modify.
Parameter keyName
The property key to set
Parameter value
The value to set {Object} the passed value.
Modifiers
@public
function trySet
trySet: <T>(root: object, path: string, value: T) => T | undefined;
Error-tolerant form of
set
. Will not blow up if any part of the chain isundefined
,null
, or destroyed.This is primarily used when syncing bindings, which may try to update after an object has been destroyed.
```javascript import { trySet } from '@ember/object';
let obj = { name: "Zoey" }; trySet(obj, "contacts.twitter", "@emberjs"); ```
trySet @ember/object
Parameter root
The object to modify.
Parameter path
The property path to set
Parameter value
The value to set
Modifiers
@public
namespace @ember/-internals/metal/lib/set_properties
module '@ember/-internals/metal/lib/set_properties' {}
function setProperties
setProperties: { <T, K extends keyof T>(obj: T, properties: Pick<T, K>): Pick<T, K>; <T extends Record<string, unknown>>(obj: object, properties: T): T;};
Set a list of properties on an object. These properties are set inside a single
beginPropertyChanges
andendPropertyChanges
batch, so observers will be buffered.```javascript import EmberObject from '@ember/object'; let anObject = EmberObject.create();
anObject.setProperties({ firstName: 'Stanley', lastName: 'Stuart', age: 21 }); ```
setProperties @ember/object
Parameter obj
Parameter properties
properties
Modifiers
@public
namespace @ember/-internals/metal/lib/tags
module '@ember/-internals/metal/lib/tags' {}
variable SELF_TAG
const SELF_TAG: string | symbol;
function markObjectAsDirty
markObjectAsDirty: (obj: object, propertyKey: string) => void;
function tagForObject
tagForObject: (obj: unknown | null) => Tag;
function tagForProperty
tagForProperty: ( obj: object, propertyKey: string | symbol, addMandatorySetter?: boolean, meta?: TagMeta) => Tag;
namespace @ember/-internals/metal/lib/tracked
module '@ember/-internals/metal/lib/tracked' {}
function tracked
tracked: { (propertyDesc: { value: any; initializer: () => any }): ExtendedMethodDecorator; (target: object, key: string): void; ( target: object, key: string, desc: PropertyDescriptor & { initializer?: any } ): PropertyDescriptor & { initializer?: any };};
Parameter dependencies
Optional dependents to be tracked.
Example 1
No dependencies
If you don't pass an argument to
@tracked
, only changes to that property will be tracked:```typescript import Component from '@glimmer/component'; import { tracked } from '@glimmer/tracking';
export default class MyComponent extends Component { remainingApples = 10 } ```
When something changes the component's
remainingApples
property, the rerender will be scheduled.Example 2
Dependents
In the case that you have a computed property that depends other properties, you want to track both so that when one of the dependents change, a rerender is scheduled.
In the following example we have two properties,
eatenApples
, andremainingApples
.```typescript import Component from '@glimmer/component'; import { tracked } from '@glimmer/tracking';
const totalApples = 100;
export default class MyComponent extends Component { eatenApples = 0
get remainingApples() { return totalApples - this.eatenApples; }
increment() { this.eatenApples = this.eatenApples + 1; } } ```
class TrackedDescriptor
class TrackedDescriptor {}
constructor
constructor(_get: () => unknown, _set: (value: unknown) => void);
method get
get: (obj: object) => unknown;
method set
set: (obj: object, _key: string, value: unknown) => void;
namespace @ember/-internals/owner
module '@ember/-internals/owner' {}
function getOwner
getOwner: (object: object) => InternalOwner | undefined;
function isFactory
isFactory: (obj: unknown) => obj is InternalFactory<object, FactoryClass>;
isFactory
Parameter obj
{Boolean}
function setOwner
setOwner: (object: object, owner: Owner) => void;
setOwner
forces a new owner on a given object instance. This is primarily useful in some testing cases.setOwner @ember/owner
Parameter object
An object instance.
Parameter object
The new owner object of the object instance. 2.3.0
Modifiers
@public
interface ContainerProxy
interface ContainerProxy extends BasicContainer {}
The interface for a container proxy, which is itself a private API used by the private
ContainerProxyMixin
as part of the base definition ofEngineInstance
.ContainerProxy @ember/owner BasicContainer
method ownerInjection
ownerInjection: () => object;
Returns an object that can be used to provide an owner to a manually created instance.
Example:
``` import { getOwner } from '@ember/application';
let owner = getOwner(this);
User.create( owner.ownerInjection(), { username: 'rwjblue' } ) ```
ownerInjection 2.3.0 {Object}
Modifiers
@public
interface DIRegistry
interface DIRegistry {}
A type registry for the DI system, which other participants in the DI system can register themselves into with declaration merging. The contract for this type is that its keys are the
Type
from aFullName
, and each value for aType
is another registry whose keys are theName
from aFullName
. The mechanic for providing a registry is [declaration merging][handbook].[handbook]: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
For example, Ember's
@ember/service
module includes this set of definitions:```ts export default class Service extends EmberObject {}
// For concrete singleton classes to be merged into. interface Registry extends Record<string, Service> {}
declare module '@ember/owner' { service: Registry; } ```
Declarations of services can then include the registry:
```ts import Service from '@ember/service';
export default class Session extends Service { login(username: string, password: string) { // ... } }
declare module '@ember/service' { interface Registry { session: Session; } } ```
Then users of the
Owner
API will be able to do things like this with strong type safety guarantees:```ts getOwner(this)?.lookup('service:session').login("hello", "1234abcd"); ```
@ember/owner
interface Factory
interface Factory<T extends object> {}
Registered factories are instantiated by having create called on them. Additionally they are singletons by default, so each time they are looked up they return the same instance.
However, that behavior can be modified with the
instantiate
andsingleton
options to theOwner.register()
method.@ember/owner Factory 4.10.0
Modifiers
@public
method create
create: (initialValues?: object) => T;
A function that will create an instance of the class with any dependencies injected.
create
Parameter initialValues
Any values to set on an instance of the class {Object} The item produced by the factory.
Modifiers
@public
interface FactoryClass
interface FactoryClass {}
property positionalParams
positionalParams?: string | string[] | undefined | null;
interface FactoryManager
interface FactoryManager<T extends object> extends Factory<T> {}
The interface representing a manager which can be used for introspection of the factory's class or for the creation of factory instances with initial properties. The manager is an object with the following properties:
-
class
- The registered or resolved class. -create
- A function that will create an instance of the class with any dependencies injected.*Note:**
FactoryManager
is *not* user-constructible; the only legal way to get aFactoryManager
is viaOwner.factoryFor
.@ember/owner FactoryManager Factory
Modifiers
@public
property class
readonly class: Factory<T>;
The registered or resolved class.
class Factory
Modifiers
@public
interface InternalFactory
interface InternalFactory< T extends object, C extends FactoryClass | object = FactoryClass> extends Factory<T> {}
The internal representation of a
Factory
, for the extra detail available for private use internally than we expose to consumers.@ember/owner InternalFactory
property class
class?: C;
class
property fullName
fullName?: FullName;
fullName String
property name
name?: string;
name String
property normalizedName
normalizedName?: string;
normalizedName String
interface Owner
interface Owner extends BasicRegistry, BasicContainer {}
Framework objects in an Ember application (components, services, routes, etc.) are created via a factory and dependency injection system. Each of these objects is the responsibility of an "owner", which handles its instantiation and manages its lifetime.
An
Owner
is not a class you construct; it is one the framework constructs for you. The normal way to get access to the relevantOwner
is using thegetOwner
function.@ember/owner BasicRegistry BasicContainer Owner 4.10.0
Modifiers
@public
interface RegisterOptions
interface RegisterOptions {}
Interface representing the options for registering an item as a factory.
@ember/owner RegisterOptions
Modifiers
@public
property instantiate
instantiate?: boolean | undefined;
Whether to instantiate the item when returning it from a lookup. Defaults to
true
.instantiate Boolean true
Modifiers
@public
property singleton
singleton?: boolean | undefined;
Whether the item is a singleton (like a service) and so should return the same instance every time, or should generate a new instance on each call. Defaults to
true
.singleton Boolean true
Modifiers
@public
interface RegistryProxy
interface RegistryProxy extends BasicRegistry {}
RegistryProxy BasicRegistry @ember/owner
method hasRegistration
hasRegistration: (fullName: FullName) => boolean;
Check if a factory is registered.
hasRegistration
Parameter fullName
{Boolean}
Modifiers
@public
method registeredOption
registeredOption: <K extends keyof RegisterOptions>( fullName: FullName, optionName: K) => RegisterOptions[K] | undefined;
Return a specific registered option for a particular factory.
registeredOption
Parameter fullName
Parameter optionName
{Object} options
Modifiers
@public
method registeredOptions
registeredOptions: (fullName: FullName) => RegisterOptions | undefined;
Return registered options for a particular factory.
registeredOptions
Parameter fullName
{Object} options
Modifiers
@public
method registeredOptionsForType
registeredOptionsForType: (type: string) => RegisterOptions | undefined;
Return the registered options for all factories of a type.
registeredOptionsForType
Parameter type
{Object} options
Modifiers
@public
method registerOptions
registerOptions: (fullName: FullName, options: RegisterOptions) => void;
Register options for a particular factory.
registerOptions
Parameter fullName
Parameter options
Modifiers
@public
method registerOptionsForType
registerOptionsForType: (type: string, options: RegisterOptions) => void;
Allow registering options for all factories of a type.
```javascript import Application from '@ember/application';
let App = Application.create(); let appInstance = App.buildInstance();
// if all of type
connection
must not be singletons appInstance.registerOptionsForType('connection', { singleton: false });appInstance.register('connection:twitter', TwitterConnection); appInstance.register('connection:facebook', FacebookConnection);
let twitter = appInstance.lookup('connection:twitter'); let twitter2 = appInstance.lookup('connection:twitter');
twitter === twitter2; // => false
let facebook = appInstance.lookup('connection:facebook'); let facebook2 = appInstance.lookup('connection:facebook');
facebook === facebook2; // => false ```
registerOptionsForType
Parameter type
Parameter options
Modifiers
@public
method resolveRegistration
resolveRegistration: ( fullName: FullName) => Factory<object> | object | undefined;
Given a fullName return the corresponding factory.
resolveRegistration
Parameter fullName
{Function} fullName's factory
Modifiers
@public
method unregister
unregister: (fullName: FullName) => void;
Unregister a factory.
```javascript import Application from '@ember/application'; import EmberObject from '@ember/object';
let App = Application.create(); let User = EmberObject.extend(); App.register('model:user', User);
App.resolveRegistration('model:user').create() instanceof User //=> true
App.unregister('model:user') App.resolveRegistration('model:user') === undefined //=> true ```
unregister
Parameter fullName
Modifiers
@public
interface Resolver
interface Resolver {}
A
Resolver
is the mechanism responsible for looking up code in your application and converting its naming conventions into the actual classes, functions, and templates that Ember needs to resolve its dependencies, for example, what template to render for a given route. It is a system that helps the app resolve the lookup of JavaScript modules agnostic of what kind of module system is used, which can be AMD, CommonJS or just plain globals. It is used to lookup routes, models, components, templates, or anything that is used in your Ember app.This interface is not a concrete class; instead, it represents the contract a custom resolver must implement. Most apps never need to think about this: in the default blueprint, this is supplied by the
ember-resolver
package.@ember/owner Resolver 4.10.0
Modifiers
@public
property knownForType
knownForType?: <Type extends string>(type: Type) => KnownForTypeResult<Type>;
knownForType
Parameter type
{Object}
Modifiers
@public
property lookupDescription
lookupDescription?: (fullName: FullName) => string;
lookupDescription
Parameter fullName
{String}
Modifiers
@public
property makeToString
makeToString?: (factory: Factory<object>, fullName: FullName) => string;
makeToString
Parameter factory
Parameter fullName
{String}
Modifiers
@public
property normalize
normalize?: (fullName: FullName) => FullName;
normalize
Parameter fullName
{String}
Modifiers
@public
property resolve
resolve: (name: string) => Factory<object> | object | undefined;
The one required method for a
Resolver
. Given a string, resolve it to aFactory
, if one exists.resolve
Parameter name
Modifiers
@public
type FullName
type FullName< Type extends string = string, Name extends string = string> = `${Type}:${Name}`;
The name for a factory consists of a namespace and the name of a specific type within that namespace, like
'service:session'
.*Note:**
FullName
is *not* a class, just a contract for strings used in the DI system. It is currently documented as a class only due to limits in our documentation infrastructure.@ember/owner FullName
Modifiers
@public
type KnownForTypeResult
type KnownForTypeResult<Type extends string> = { [Key in FullName<Type, string>]: boolean | undefined;};
A record mapping all known items of a given type: if the item is known it will be
true
; otherwise it will befalse
orundefined
.
namespace @ember/-internals/routing
module '@ember/-internals/routing' {}
function controllerFor
controllerFor: ( container: Container, controllerName: string, lookupOptions: RegisterOptions) => InternalFactory<object, FactoryClass> | object | undefined;
Finds a controller instance.
Ember controllerFor
function generateController
generateController: (owner: Owner, controllerName: string) => Controller;
Generates and instantiates a controller extending from
controller:basic
if present, orController
if not.Ember generateController 1.3.0
function generateControllerFactory
generateControllerFactory: ( owner: Owner, controllerName: string) => InternalFactory<{}>;
Generates a controller factory
Ember generateControllerFactory
class RouterDSL
class DSLImpl implements DSL {}
constructor
constructor(name: string, options: DSLImplOptions);
property enableLoadingSubstates
enableLoadingSubstates: boolean;
property explicitIndex
explicitIndex: boolean;
property matches
matches: Object[];
property options
options: DSLImplOptions;
property parent
parent: string;
method generate
generate: () => MatchCallback;
method mount
mount: (_name: string, options?: MountOptions) => void;
method push
push: ( url: string, name: string, callback?: MatchCallback, serialize?: (model: {}, params: string[]) => { [key: string]: unknown }) => void;
method route
route: { (name: string): void; (name: string, callback: DSLCallback): void; (name: string, options: RouteOptions): void; (name: string, options: RouteOptions, callback: DSLCallback): void;};
namespace @ember/-internals/runtime
module '@ember/-internals/runtime' {}
variable ActionHandler
const ActionHandler: Mixin;
variable Comparable
const Comparable: Mixin;
variable ContainerProxyMixin
const ContainerProxyMixin: Mixin;
variable MutableEnumerable
const MutableEnumerable: Mixin;
variable RegistryProxyMixin
const RegistryProxyMixin: Mixin;
variable TargetActionSupport
const TargetActionSupport: Mixin;
function onerrorDefault
onerrorDefault: (reason: unknown) => void;
interface ActionHandler
interface ActionHandler {}
Ember.ActionHandler
is available on some familiar classes includingRoute
,Component
, andController
. (Internally the mixin is used byEmber.CoreView
,Ember.ControllerMixin
, andRoute
and available to the above classes through inheritance.)ActionHandler Ember
interface Comparable
interface Comparable {}
Implements some standard methods for comparing objects. Add this mixin to any class you create that can compare its instances.
You should implement the
compare()
method.Comparable Ember Ember 0.9
property compare
compare: ((a: unknown, b: unknown) => -1 | 0 | 1) | null;
interface ContainerProxyMixin
interface ContainerProxyMixin extends ContainerProxy {}
ContainerProxyMixin is used to provide public access to specific container functionality.
ContainerProxyMixin ContainerProxy
interface MutableEnumerable
interface MutableEnumerable extends Enumerable {}
The methods in this mixin have been moved to MutableArray. This mixin has been intentionally preserved to avoid breaking MutableEnumerable.detect checks until the community migrates away from them.
MutableEnumerable Ember Enumerable
interface RegistryProxyMixin
interface RegistryProxyMixin extends RegistryProxy {}
RegistryProxyMixin is used to provide public access to specific registry functionality.
RegistryProxyMixin RegistryProxy
interface TargetActionSupport
interface TargetActionSupport {}
Ember.TargetActionSupport
is a mixin that can be included in a class to add atriggerAction
method with semantics similar to the Handlebars{{action}}
helper. 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 Components.TargetActionSupport Ember Mixin
property action
action: string | null;
property actionContext
actionContext: unknown;
property actionContextObject
actionContextObject: unknown;
property target
target: unknown;
method triggerAction
triggerAction: (opts?: object) => unknown;
namespace @ember/-internals/runtime/lib/ext/rsvp
module '@ember/-internals/runtime/lib/ext/rsvp' {}
function onerrorDefault
onerrorDefault: (reason: unknown) => void;
namespace @ember/-internals/runtime/lib/mixins/-proxy
module '@ember/-internals/runtime/lib/mixins/-proxy' {}
variable ProxyMixin
const ProxyMixin: Mixin;
function contentFor
contentFor: <T>(proxy: ProxyMixin<T>) => T | null;
interface ProxyMixin
interface ProxyMixin<T = unknown> {}
Ember.ProxyMixin
forwards all properties not defined by the proxy itself to a proxiedcontent
object. See ObjectProxy for more details.ProxyMixin Ember
property content
content: T | null;
The object whose properties will be forwarded.
content {unknown} null
Modifiers
@public
property isTruthy
isTruthy: boolean;
method setUnknownProperty
setUnknownProperty: { <K extends keyof T>(key: K, value: T[K]): T[K]; <V>(key: string, value: V): V;};
method unknownProperty
unknownProperty: { <K extends keyof T>(key: K): T[K] | undefined; (key: string): unknown;};
method willDestroy
willDestroy: () => void;
namespace @ember/-internals/runtime/lib/mixins/action_handler
module '@ember/-internals/runtime/lib/mixins/action_handler' {}
variable ActionHandler
const ActionHandler: Mixin;
interface ActionHandler
interface ActionHandler {}
Ember.ActionHandler
is available on some familiar classes includingRoute
,Component
, andController
. (Internally the mixin is used byEmber.CoreView
,Ember.ControllerMixin
, andRoute
and available to the above classes through inheritance.)ActionHandler Ember
namespace @ember/-internals/runtime/lib/mixins/comparable
module '@ember/-internals/runtime/lib/mixins/comparable' {}
variable Comparable
const Comparable: Mixin;
interface Comparable
interface Comparable {}
Implements some standard methods for comparing objects. Add this mixin to any class you create that can compare its instances.
You should implement the
compare()
method.Comparable Ember Ember 0.9
property compare
compare: ((a: unknown, b: unknown) => -1 | 0 | 1) | null;
namespace @ember/-internals/runtime/lib/mixins/container_proxy
module '@ember/-internals/runtime/lib/mixins/container_proxy' {}
variable ContainerProxyMixin
const ContainerProxyMixin: Mixin;
interface ContainerProxyMixin
interface ContainerProxyMixin extends ContainerProxy {}
ContainerProxyMixin is used to provide public access to specific container functionality.
ContainerProxyMixin ContainerProxy
namespace @ember/-internals/runtime/lib/mixins/registry_proxy
module '@ember/-internals/runtime/lib/mixins/registry_proxy' {}
variable RegistryProxyMixin
const RegistryProxyMixin: Mixin;
interface RegistryProxyMixin
interface RegistryProxyMixin extends RegistryProxy {}
RegistryProxyMixin is used to provide public access to specific registry functionality.
RegistryProxyMixin RegistryProxy
namespace @ember/-internals/runtime/lib/mixins/target_action_support
module '@ember/-internals/runtime/lib/mixins/target_action_support' {}
variable TargetActionSupport
const TargetActionSupport: Mixin;
interface TargetActionSupport
interface TargetActionSupport {}
Ember.TargetActionSupport
is a mixin that can be included in a class to add atriggerAction
method with semantics similar to the Handlebars{{action}}
helper. 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 Components.TargetActionSupport Ember Mixin
property action
action: string | null;
property actionContext
actionContext: unknown;
property actionContextObject
actionContextObject: unknown;
property target
target: unknown;
method triggerAction
triggerAction: (opts?: object) => unknown;
namespace @ember/-internals/string
module '@ember/-internals/string' {}
function classify
classify: (str: string) => string;
Returns the UpperCamelCase form of a string.
```javascript import { classify } from '@ember/string';
classify('innerHTML'); // 'InnerHTML' classify('action_name'); // 'ActionName' classify('css-class-name'); // 'CssClassName' classify('my favorite items'); // 'MyFavoriteItems' classify('private-docs/owner-invoice'); // 'PrivateDocs/OwnerInvoice' ```
classify
Parameter str
the string to classify {String} the classified string
function dasherize
dasherize: (str: string) => string;
Replaces underscores, spaces, or camelCase with dashes.
```javascript import { dasherize } from '@ember/-internals/string';
dasherize('innerHTML'); // 'inner-html' dasherize('action_name'); // 'action-name' dasherize('css-class-name'); // 'css-class-name' dasherize('my favorite items'); // 'my-favorite-items' dasherize('privateDocs/ownerInvoice'; // 'private-docs/owner-invoice' ```
dasherize
Parameter str
The string to dasherize. {String} the dasherized string.
namespace @ember/-internals/utility-types
module '@ember/-internals/utility-types' {}
class Opaque
class Opaque<Data> {}
type AnyFn
type AnyFn = (...args: any[]) => any;
type MethodNamesOf
type MethodNamesOf<T> = keyof MethodsOf<T>;
type MethodParams
type MethodParams<T, M extends MethodNamesOf<T>> = Parameters<MethodsOf<T>[M]>;
type MethodReturns
type MethodReturns<T, M extends MethodNamesOf<T>> = ReturnType<MethodsOf<T>[M]>;
type MethodsOf
type MethodsOf<T> = { [K in keyof T as T[K] extends AnyFn ? K : never]: T[K] extends AnyFn ? T[K] : never;};
type Nullable
type Nullable<T> = T | null;
type OmitFirst
type OmitFirst<F> = F extends [any, ...infer R] ? R : [];
namespace @ember/-internals/utils
module '@ember/-internals/utils' {}
variable getDebugName
let getDebugName: (value: any) => string;
variable GUID_KEY
const GUID_KEY: string;
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.
GUID_KEY Ember String
variable setupMandatorySetter
let setupMandatorySetter: (tag: Tag, obj: object, keyName: string | symbol) => void;
variable setWithMandatorySetter
let setWithMandatorySetter: (obj: object, keyName: string, value: any) => void;
variable symbol
const symbol: SymbolConstructor;
variable teardownMandatorySetter
let teardownMandatorySetter: (obj: object, keyName: string | symbol) => void;
function canInvoke
canInvoke: (obj: unknown, methodName: string) => boolean;
Checks to see if the
methodName
exists on theobj
.```javascript let foo = { bar: function() { return 'bar'; }, baz: null };
Ember.canInvoke(foo, 'bar'); // true Ember.canInvoke(foo, 'baz'); // false Ember.canInvoke(foo, 'bat'); // false ```
canInvoke Ember
Parameter obj
The object to check for the method
Parameter methodName
The method name to check for {Boolean}
function checkHasSuper
checkHasSuper: (func: Function) => boolean;
function dictionary
dictionary: <T>(parent: { [key: string]: T }) => { [key: string]: T };
function enumerableSymbol
enumerableSymbol: (debugName: string) => string;
function generateGuid
generateGuid: (obj: object, prefix?: string) => String;
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
guidFor(obj)
, which return an existing guid if available.generateGuid @ember/object/internals
Parameter 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.
Parameter prefix
Prefix to place in front of the guid. Useful when you want to separate the guid into separate namespaces. {String} the guid
function getName
getName: (obj: object) => string | undefined;
function guidFor
guidFor: (value: any | null | undefined) => string;
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,
EmberObject
-based or not.You can also use this method on DOM Element objects.
guidFor @ember/object/internals
Parameter obj
any object, string, number, Element, or primitive {String} the unique guid for this instance.
Modifiers
@public
function intern
intern: <S extends string>(str: S) => S;
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â„¢
{String} interned version of the provided string
function isInternalSymbol
isInternalSymbol: (possibleSymbol: string) => boolean;
function isObject
isObject: (value: any | null | undefined) => value is object;
Returns whether Type(value) is Object.
Useful for checking whether a value is a valid WeakMap key.
Refs: https://tc39.github.io/ecma262/#sec-typeof-operator-runtime-semantics-evaluation https://tc39.github.io/ecma262/#sec-weakmap.prototype.set
isObject
function isProxy
isProxy: (value: unknown) => value is ProxyMixin<unknown>;
function lookupDescriptor
lookupDescriptor: ( obj: object, keyName: string | symbol) => PropertyDescriptor | null;
function observerListenerMetaFor
observerListenerMetaFor: (fn: Function) => ObserverListenerMeta | undefined;
function ROOT
ROOT: () => void;
function setListeners
setListeners: (func: Function, listeners: string[]) => void;
function setName
setName: (obj: object, name: string) => void;
function setObservers
setObservers: ( func: Function, observers: { paths: string[]; sync: boolean }) => void;
function setProxy
setProxy: (object: ProxyMixin<unknown>) => void;
function toString
toString: (obj: any | undefined | null) => string;
function uuid
uuid: () => number;
Generates a universally unique identifier. This method is used internally by Ember for assisting with the generation of GUID's and other unique identifiers.
{Number} [description]
Modifiers
@public
function wrap
wrap: (func: Function, superFunc: Function) => Function;
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.wrap Ember
Parameter func
The function to call
Parameter superFunc
The super function. {Function} wrapped function.
namespace @ember/-internals/utils/lib/cache
module '@ember/-internals/utils/lib/cache' {}
namespace @ember/-internals/utils/lib/dictionary
module '@ember/-internals/utils/lib/dictionary' {}
function makeDictionary
makeDictionary: <T>(parent: { [key: string]: T }) => { [key: string]: T };
namespace @ember/-internals/utils/lib/get-debug-name
module '@ember/-internals/utils/lib/get-debug-name' {}
variable getDebugName
let getDebugName: (value: any) => string;
namespace @ember/-internals/utils/lib/guid
module '@ember/-internals/utils/lib/guid' {}
variable GUID_KEY
const GUID_KEY: string;
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.
GUID_KEY Ember String
function generateGuid
generateGuid: (obj: object, prefix?: string) => String;
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
guidFor(obj)
, which return an existing guid if available.generateGuid @ember/object/internals
Parameter 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.
Parameter prefix
Prefix to place in front of the guid. Useful when you want to separate the guid into separate namespaces. {String} the guid
function guidFor
guidFor: (value: any | null | undefined) => string;
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,
EmberObject
-based or not.You can also use this method on DOM Element objects.
guidFor @ember/object/internals
Parameter obj
any object, string, number, Element, or primitive {String} the unique guid for this instance.
Modifiers
@public
function uuid
uuid: () => number;
Generates a universally unique identifier. This method is used internally by Ember for assisting with the generation of GUID's and other unique identifiers.
{Number} [description]
Modifiers
@public
namespace @ember/-internals/utils/lib/intern
module '@ember/-internals/utils/lib/intern' {}
function intern
intern: <S extends string>(str: S) => S;
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â„¢
{String} interned version of the provided string
namespace @ember/-internals/utils/lib/invoke
module '@ember/-internals/utils/lib/invoke' {}
function canInvoke
canInvoke: (obj: unknown, methodName: string) => boolean;
Checks to see if the
methodName
exists on theobj
.```javascript let foo = { bar: function() { return 'bar'; }, baz: null };
Ember.canInvoke(foo, 'bar'); // true Ember.canInvoke(foo, 'baz'); // false Ember.canInvoke(foo, 'bat'); // false ```
canInvoke Ember
Parameter obj
The object to check for the method
Parameter methodName
The method name to check for {Boolean}
namespace @ember/-internals/utils/lib/is_proxy
module '@ember/-internals/utils/lib/is_proxy' {}
namespace @ember/-internals/utils/lib/lookup-descriptor
module '@ember/-internals/utils/lib/lookup-descriptor' {}
function lookupDescriptor
lookupDescriptor: ( obj: object, keyName: string | symbol) => PropertyDescriptor | null;
namespace @ember/-internals/utils/lib/mandatory-setter
module '@ember/-internals/utils/lib/mandatory-setter' {}
variable setupMandatorySetter
let setupMandatorySetter: (tag: Tag, obj: object, keyName: string | symbol) => void;
variable setWithMandatorySetter
let setWithMandatorySetter: (obj: object, keyName: string, value: any) => void;
variable teardownMandatorySetter
let teardownMandatorySetter: (obj: object, keyName: string | symbol) => void;
namespace @ember/-internals/utils/lib/name
module '@ember/-internals/utils/lib/name' {}
namespace @ember/-internals/utils/lib/spec
module '@ember/-internals/utils/lib/spec' {}
function isObject
isObject: (value: any | null | undefined) => value is object;
Returns whether Type(value) is Object.
Useful for checking whether a value is a valid WeakMap key.
Refs: https://tc39.github.io/ecma262/#sec-typeof-operator-runtime-semantics-evaluation https://tc39.github.io/ecma262/#sec-weakmap.prototype.set
isObject
namespace @ember/-internals/utils/lib/super
module '@ember/-internals/utils/lib/super' {}
function checkHasSuper
checkHasSuper: (func: Function) => boolean;
function observerListenerMetaFor
observerListenerMetaFor: (fn: Function) => ObserverListenerMeta | undefined;
function ROOT
ROOT: () => void;
function setListeners
setListeners: (func: Function, listeners: string[]) => void;
function setObservers
setObservers: ( func: Function, observers: { paths: string[]; sync: boolean }) => void;
function wrap
wrap: (func: Function, superFunc: Function) => Function;
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.wrap Ember
Parameter func
The function to call
Parameter superFunc
The super function. {Function} wrapped function.
namespace @ember/-internals/utils/lib/symbol
module '@ember/-internals/utils/lib/symbol' {}
variable symbol
const symbol: SymbolConstructor;
function enumerableSymbol
enumerableSymbol: (debugName: string) => string;
function isInternalSymbol
isInternalSymbol: (possibleSymbol: string) => boolean;
namespace @ember/-internals/utils/lib/to-string
module '@ember/-internals/utils/lib/to-string' {}
function toString
toString: (obj: any | undefined | null) => string;
namespace @ember/-internals/views
module '@ember/-internals/views' {}
variable ActionSupport
const ActionSupport: Mixin;
variable ChildViewsSupport
const ChildViewsSupport: Mixin;
variable ClassNamesSupport
const ClassNamesSupport: Mixin;
variable ComponentLookup
const ComponentLookup: Readonly<typeof EmberObject> & (new ( owner?: import('@ember/-internals/owner').default | undefined ) => EmberObject) & { componentFor( name: string, owner: InternalOwner ): import('@ember/-internals/owner').FactoryManager<object> | undefined; layoutFor( name: string, owner: InternalOwner, options: RegisterOptions ): unknown; };
variable MUTABLE_CELL
const MUTABLE_CELL: Symbol;
variable ViewMixin
const ViewMixin: Mixin;
variable ViewStateSupport
const ViewStateSupport: Mixin;
function ActionManager
ActionManager: typeof ActionManager;
ember
function addChildView
addChildView: (parent: View, child: View) => void;
function clearElementView
clearElementView: (element: Element) => void;
function clearViewElement
clearViewElement: (view: View) => void;
function constructStyleDeprecationMessage
constructStyleDeprecationMessage: (affectedStyle: string) => string;
function getChildViews
getChildViews: (view: View) => View[];
getChildViews
Parameter view
function getElementView
getElementView: (element: Element) => Nullable<View>;
function getRootViews
getRootViews: (owner: InternalOwner) => View[];
getRootViews
Parameter owner
function getViewBoundingClientRect
getViewBoundingClientRect: (view: View) => ClientRect | DOMRect;
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 Inspector and may not work on older browsers.
getViewBoundingClientRect
Parameter view
function getViewBounds
getViewBounds: (view: View) => { parentElement: import('@simple-dom/interface').SimpleElement; firstNode: import('@simple-dom/interface').SimpleNode; lastNode: import('@simple-dom/interface').SimpleNode;};
getViewBounds
Parameter view
function getViewClientRects
getViewClientRects: (view: View) => DOMRectList;
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.
getViewClientRects
Parameter view
function getViewElement
getViewElement: (view: View) => Nullable<Element>;
getViewElement
Parameter view
function getViewId
getViewId: (view: View) => string;
getViewId
Parameter view
function isSimpleClick
isSimpleClick: (event: Event) => boolean;
ember
function setElementView
setElementView: (element: Element, view: View) => void;
function setViewElement
setViewElement: (view: View, element: Element) => void;
class CoreView
class CoreView extends CoreView_base {}
property isView
isView: boolean;
property isViewFactory
static isViewFactory: boolean;
property parentView
parentView: View;
If the view is currently inserted into the DOM of a parent view, this property will point to the parent of the view.
parentView Ember.View null
property renderer
renderer: Renderer;
method init
init: (properties: object | undefined) => void;
method instrumentDetails
instrumentDetails: (hash: Record<string, unknown>) => Record<string, unknown>;
class EventDispatcher
class EventDispatcher extends EmberObject {}
Ember.EventDispatcher
handles delegating browser events to their correspondingEmber.Views.
For example, when you click on a view,Ember.EventDispatcher
ensures that that view'smouseDown
method gets called.EventDispatcher Ember EmberObject
property events
events: Record<string, string>;
The set of events names (and associated handler function names) to be setup and dispatched by the
EventDispatcher
. Modifications to this list can be done at setup time, generally via theApplication.customEvents
hash.To add new events to be listened to:
```javascript import Application from '@ember/application';
let App = Application.create({ customEvents: { paste: 'paste' } }); ```
To prevent default events from being listened to:
```javascript import Application from '@ember/application';
let App = Application.create({ customEvents: { mouseenter: null, mouseleave: null } }); ``` events Object
property finalEventNameMapping
finalEventNameMapping: Record<string, string>;
property lazyEvents
lazyEvents: Map<string, string>;
property rootElement
rootElement: string | Element;
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.
rootElement DOMElement 'body'
method destroy
destroy: () => any;
method setup
setup: ( addedEvents: Record<string, string | null>, _rootElement: string | Element | null) => void;
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'sroot
property.setup
Parameter addedEvents
method setupHandler
setupHandler: ( rootElement: Element, event: string, eventName: string | null) => void;
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.setupHandler
Parameter rootElement
Parameter event
the name of the event in the browser
Parameter eventName
the name of the method to call on the view
method setupHandlerForBrowserEvent
setupHandlerForBrowserEvent: (event: string) => void;
Setup event listeners for the given browser event name
setupHandlerForBrowserEvent
Parameter event
the name of the event in the browser
method setupHandlerForEmberEvent
setupHandlerForEmberEvent: (eventName: string) => void;
Setup event listeners for the given Ember event name (camel case)
setupHandlerForEmberEvent
Parameter eventName
method toString
toString: () => string;
interface ActionSupport
interface ActionSupport {}
ActionSupport Ember
method send
send: (actionName: string, ...args: unknown[]) => void;
interface ChildViewsSupport
interface ChildViewsSupport {}
property childViews
readonly childViews: View[];
method appendChild
appendChild: (view: View) => void;
interface ClassNamesSupport
interface ClassNamesSupport {}
ClassNamesSupport Ember
property classNameBindings
classNameBindings: string[];
property classNames
classNames: string[];
interface CoreView
interface CoreView extends Evented, ActionHandler, View {}
Ember.CoreView
is an abstract class that exists to give view-like behavior to both Ember's main view classComponent
and other classes that don't need the full functionality ofComponent
.Unless you have specific needs for
CoreView
, you will useComponent
in your applications.CoreView Ember EmberObject
Deprecated
Use
Component
instead. Evented Ember.ActionHandler
interface ViewMixin
interface ViewMixin {}
ViewMixin Ember
property element
element: Element;
property elementId
elementId: string | null;
property tagName
tagName: string | null;
method append
append: () => this;
method appendTo
appendTo: (selector: string | Element | SimpleElement) => this;
method didInsertElement
didInsertElement: () => void;
method handleEvent
handleEvent: (eventName: string, evt: Event) => boolean;
method parentViewDidChange
parentViewDidChange: () => void;
method rerender
rerender: () => unknown;
method willClearRender
willClearRender: () => void;
method willDestroyElement
willDestroyElement: () => void;
method willInsertElement
willInsertElement: () => void;
interface ViewStateSupport
interface ViewStateSupport {}
namespace @ember/-internals/views.ActionManager
namespace @ember/-internals/views.ActionManager {}
variable registeredActions
var registeredActions: Record<string, ActionState>;
namespace @ember/-internals/views/lib/compat/attrs
module '@ember/-internals/views/lib/compat/attrs' {}
variable MUTABLE_CELL
const MUTABLE_CELL: Symbol;
namespace @ember/-internals/views/lib/compat/fallback-view-registry
module '@ember/-internals/views/lib/compat/fallback-view-registry' {}
variable _default
const _default: { [key: string]: unknown };
namespace @ember/-internals/views/lib/component_lookup
module '@ember/-internals/views/lib/component_lookup' {}
variable _default
const _default: Readonly<typeof EmberObject> & (new ( owner?: import('@ember/-internals/owner').default | undefined ) => EmberObject) & { componentFor( name: string, owner: InternalOwner ): import('@ember/-internals/owner').FactoryManager<object> | undefined; layoutFor( name: string, owner: InternalOwner, options: RegisterOptions ): unknown; };
namespace @ember/-internals/views/lib/mixins/action_support
module '@ember/-internals/views/lib/mixins/action_support' {}
variable ActionSupport
const ActionSupport: Mixin;
interface ActionSupport
interface ActionSupport {}
ActionSupport Ember
method send
send: (actionName: string, ...args: unknown[]) => void;
namespace @ember/-internals/views/lib/mixins/child_views_support
module '@ember/-internals/views/lib/mixins/child_views_support' {}
variable ChildViewsSupport
const ChildViewsSupport: Mixin;
interface ChildViewsSupport
interface ChildViewsSupport {}
property childViews
readonly childViews: View[];
method appendChild
appendChild: (view: View) => void;
namespace @ember/-internals/views/lib/mixins/class_names_support
module '@ember/-internals/views/lib/mixins/class_names_support' {}
variable ClassNamesSupport
const ClassNamesSupport: Mixin;
interface ClassNamesSupport
interface ClassNamesSupport {}
ClassNamesSupport Ember
property classNameBindings
classNameBindings: string[];
property classNames
classNames: string[];
namespace @ember/-internals/views/lib/mixins/view_state_support
module '@ember/-internals/views/lib/mixins/view_state_support' {}
variable ViewStateSupport
const ViewStateSupport: Mixin;
interface ViewStateSupport
interface ViewStateSupport {}
namespace @ember/-internals/views/lib/mixins/view_support
module '@ember/-internals/views/lib/mixins/view_support' {}
variable ViewMixin
const ViewMixin: Mixin;
interface ViewMixin
interface ViewMixin {}
ViewMixin Ember
property element
element: Element;
property elementId
elementId: string | null;
property tagName
tagName: string | null;
method append
append: () => this;
method appendTo
appendTo: (selector: string | Element | SimpleElement) => this;
method didInsertElement
didInsertElement: () => void;
method handleEvent
handleEvent: (eventName: string, evt: Event) => boolean;
method parentViewDidChange
parentViewDidChange: () => void;
method rerender
rerender: () => unknown;
method willClearRender
willClearRender: () => void;
method willDestroyElement
willDestroyElement: () => void;
method willInsertElement
willInsertElement: () => void;
namespace @ember/-internals/views/lib/system/action_manager
module '@ember/-internals/views/lib/system/action_manager' {}
function ActionManager
ActionManager: typeof ActionManager;
ember
namespace @ember/-internals/views/lib/system/action_manager.ActionManager
namespace @ember/-internals/views/lib/system/action_manager.ActionManager {}
variable registeredActions
var registeredActions: Record<string, ActionState>;
namespace @ember/-internals/views/lib/system/event_dispatcher
module '@ember/-internals/views/lib/system/event_dispatcher' {}
class EventDispatcher
class EventDispatcher extends EmberObject {}
Ember.EventDispatcher
handles delegating browser events to their correspondingEmber.Views.
For example, when you click on a view,Ember.EventDispatcher
ensures that that view'smouseDown
method gets called.EventDispatcher Ember EmberObject
property events
events: Record<string, string>;
The set of events names (and associated handler function names) to be setup and dispatched by the
EventDispatcher
. Modifications to this list can be done at setup time, generally via theApplication.customEvents
hash.To add new events to be listened to:
```javascript import Application from '@ember/application';
let App = Application.create({ customEvents: { paste: 'paste' } }); ```
To prevent default events from being listened to:
```javascript import Application from '@ember/application';
let App = Application.create({ customEvents: { mouseenter: null, mouseleave: null } }); ``` events Object
property finalEventNameMapping
finalEventNameMapping: Record<string, string>;
property lazyEvents
lazyEvents: Map<string, string>;
property rootElement
rootElement: string | Element;
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.
rootElement DOMElement 'body'
method destroy
destroy: () => any;
method setup
setup: ( addedEvents: Record<string, string | null>, _rootElement: string | Element | null) => void;
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'sroot
property.setup
Parameter addedEvents
method setupHandler
setupHandler: ( rootElement: Element, event: string, eventName: string | null) => void;
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.setupHandler
Parameter rootElement
Parameter event
the name of the event in the browser
Parameter eventName
the name of the method to call on the view
method setupHandlerForBrowserEvent
setupHandlerForBrowserEvent: (event: string) => void;
Setup event listeners for the given browser event name
setupHandlerForBrowserEvent
Parameter event
the name of the event in the browser
method setupHandlerForEmberEvent
setupHandlerForEmberEvent: (eventName: string) => void;
Setup event listeners for the given Ember event name (camel case)
setupHandlerForEmberEvent
Parameter eventName
method toString
toString: () => string;
namespace @ember/-internals/views/lib/system/utils
module '@ember/-internals/views/lib/system/utils' {}
variable elMatches
const elMatches: (selectors: string) => boolean;
Determines if the element matches the specified selector.
matches
Parameter el
Parameter selector
function addChildView
addChildView: (parent: View, child: View) => void;
function clearElementView
clearElementView: (element: Element) => void;
function clearViewElement
clearViewElement: (view: View) => void;
function collectChildViews
collectChildViews: (view: View, registry: Dict<View>) => View[];
function constructStyleDeprecationMessage
constructStyleDeprecationMessage: (affectedStyle: string) => string;
function contains
contains: (a: Node, b: Node) => boolean;
function getChildViews
getChildViews: (view: View) => View[];
getChildViews
Parameter view
function getElementView
getElementView: (element: Element) => Nullable<View>;
function getRootViews
getRootViews: (owner: InternalOwner) => View[];
getRootViews
Parameter owner
function getViewBoundingClientRect
getViewBoundingClientRect: (view: View) => ClientRect | DOMRect;
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 Inspector and may not work on older browsers.
getViewBoundingClientRect
Parameter view
function getViewBounds
getViewBounds: (view: View) => { parentElement: import('@simple-dom/interface').SimpleElement; firstNode: import('@simple-dom/interface').SimpleNode; lastNode: import('@simple-dom/interface').SimpleNode;};
getViewBounds
Parameter view
function getViewClientRects
getViewClientRects: (view: View) => DOMRectList;
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.
getViewClientRects
Parameter view
function getViewElement
getViewElement: (view: View) => Nullable<Element>;
getViewElement
Parameter view
function getViewId
getViewId: (view: View) => string;
getViewId
Parameter view
function getViewRange
getViewRange: (view: View) => Range;
getViewRange
Parameter view
function initChildViews
initChildViews: (view: View) => Set<string>;
function isSimpleClick
isSimpleClick: (event: Event) => boolean;
ember
function matches
matches: (el: Element, selector: string) => boolean;
function setElementView
setElementView: (element: Element, view: View) => void;
function setViewElement
setViewElement: (view: View, element: Element) => void;
namespace @ember/-internals/views/lib/views/core_view
module '@ember/-internals/views/lib/views/core_view' {}
class CoreView
class CoreView extends CoreView_base {}
property isView
isView: boolean;
property isViewFactory
static isViewFactory: boolean;
property parentView
parentView: View;
If the view is currently inserted into the DOM of a parent view, this property will point to the parent of the view.
parentView Ember.View null
property renderer
renderer: Renderer;
method init
init: (properties: object | undefined) => void;
method instrumentDetails
instrumentDetails: (hash: Record<string, unknown>) => Record<string, unknown>;
interface CoreView
interface CoreView extends Evented, ActionHandler, View {}
Ember.CoreView
is an abstract class that exists to give view-like behavior to both Ember's main view classComponent
and other classes that don't need the full functionality ofComponent
.Unless you have specific needs for
CoreView
, you will useComponent
in your applications.CoreView Ember EmberObject
Deprecated
Use
Component
instead. Evented Ember.ActionHandler
namespace @ember/-internals/views/lib/views/states
module '@ember/-internals/views/lib/views/states' {}
variable states
const states: Readonly<{ preRender: Readonly<ViewState>; inDOM: Readonly<ViewState>; hasElement: Readonly<ViewState>; destroying: Readonly<ViewState>;}>;
interface ViewState
interface ViewState {}
method appendChild
appendChild: () => void;
method destroy
destroy: (view: Component) => void;
method enter
enter: (view: Component) => void;
method exit
exit: (view: Component) => void;
method handleEvent
handleEvent: (view: Component, eventName: string, event: Event) => boolean;
method rerender
rerender: (view: Component) => void;
namespace @ember/application
module '@ember/application' {}
variable setOwner
const setOwner: (object: object, owner: Owner) => void;
Deprecated
Use
import { setOwner } from '@ember/owner';
instead.
function getOwner
getOwner: (object: object) => import('@ember/owner').default | undefined;
Deprecated
Use
import { getOwner } from '@ember/owner';
instead.
function onLoad
onLoad: (name: string, callback: (obj: any) => void) => void;
Detects when a specific package of Ember (e.g. 'Application') has fully loaded and is available for extension.
The provided
callback
will be called with thename
passed resolved from a string into the object:``` javascript import { onLoad } from '@ember/application';
onLoad('Ember.Application' function(hbars) { hbars.registerHelper(...); }); ```
onLoad @ember/application
Parameter name
name of hook
Parameter callback
callback to be called
function runLoadHooks
runLoadHooks: (name: string, object: unknown) => void;
Called when an Ember.js package (e.g Application) has finished loading. Triggers any callbacks registered for this event.
runLoadHooks @ember/application
Parameter name
name of hook
Parameter object
object to pass to callbacks
class Application
class Application extends Engine {}
An instance of
Application
is the starting point for every Ember application. It instantiates, initializes and coordinates the objects that make up your app.Each Ember app has one and only one
Application
object. Although Ember CLI creates this object implicitly, theApplication
class is defined in theapp/app.js
. You can define aready
method on theApplication
class, which will be run by Ember when the application is initialized.```app/app.js export default class App extends Application { ready() { // your code here } } ```
Because
Application
ultimately inherits fromEmber.Namespace
, any classes you create will have useful string representations when callingtoString()
. See theEmber.Namespace
documentation for more information.While you can think of your
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. It is also important to understand that anApplication
is different from anApplicationInstance
. Refer to the Guides to understand the difference between these.### 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 amousedown
listener on thebody
.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 theirmouseDown
method as it goes.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, thekeypress
event causes thekeyPress
method on the view to be called, thedblclick
event causesdoubleClick
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:```app/app.js import Application from '@ember/application';
export default class App extends Application { customEvents = { // add support for the paste event paste: 'paste' } } ```
To prevent Ember from setting up a listener for a default event, specify the event name with a
null
value in thecustomEvents
property:```app/app.js import Application from '@ember/application';
export default class App extends Application { customEvents = { // prevent listeners for mouseenter/mouseleave events mouseenter: null, mouseleave: null } } ```
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'srootElement
property:```app/app.js import Application from '@ember/application';
export default class App extends Application { rootElement = '#ember-app' } ```
The
rootElement
can be either a DOM element or a CSS 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 events Ember components use, see
[components/handling-events](https://guides.emberjs.com/release/components/handling-events/#toc_event-names).
### Initializers
To add behavior to the Application's boot process, you can define initializers in the
app/initializers
directory, or withember generate initializer
using Ember CLI. These files should export a namedinitialize
function which will receive the createdapplication
object as its first argument.```javascript export function initialize(application) { // application.inject('route', 'foo', 'service:foo'); } ```
Application initializers can be used for a variety of reasons including:
- setting up external libraries - injecting dependencies - setting up event listeners in embedded apps - deferring the boot process using the
deferReadiness
andadvanceReadiness
APIs.### Routing
In addition to creating your application's router,
Application
is also responsible for telling the router when to start routing. Transitions between routes can be logged with theLOG_TRANSITIONS
flag, and more detailed intra-transition logging can be logged with theLOG_TRANSITIONS_INTERNAL
flag:```javascript import Application from '@ember/application';
let App = 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'sdeferReadiness()
method. Once routing can begin, call theadvanceReadiness()
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.Application Engine
Modifiers
@public
property autoboot
autoboot: boolean;
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 tofalse
and control the precise timing and behavior of the boot process.autoboot Boolean true
property customEvents
customEvents: Record<string, string>;
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 asmousedown
andkeyup
, and delegates them to your application'sEmber.View
instances.If you would like additional bubbling events to be delegated to your views, set your
Application
'scustomEvents
property to a hash containing the DOM event name as the key and the corresponding view method name as the value. Setting an event to a value ofnull
will prevent a default event listener from being added for that event.To add new events to be listened to:
```app/app.js import Application from '@ember/application';
let App = Application.extend({ customEvents: { // add support for the paste event paste: 'paste' } }); ```
To prevent default events from being listened to:
```app/app.js import Application from '@ember/application';
let App = Application.extend({ customEvents: { // remove support for mouseenter / mouseleave events mouseenter: null, mouseleave: null } }); ``` customEvents Object null
Modifiers
@public
property eventDispatcher
eventDispatcher: EventDispatcher;
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.eventDispatcher Ember.EventDispatcher null
Modifiers
@public
property initializer
static initializer: ( this: typeof Engine, initializer: import('@ember/engine').Initializer<Application>) => void;
property instanceInitializer
static instanceInitializer: ( this: typeof Engine, initializer: import('@ember/engine').Initializer<ApplicationInstance>) => void;
property rootElement
rootElement: any;
The root DOM element of the Application. This can be specified as an element or a [selector string](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors#reference_table_of_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.rootElement DOMElement 'body'
Modifiers
@public
property Router
Router?: typeof Router;
method advanceReadiness
advanceReadiness: () => void;
Call
advanceReadiness
after any asynchronous setup logic has completed. Each call todeferReadiness
must be matched by a call toadvanceReadiness
or the application will never become ready and routing will not begin.advanceReadiness
See Also
{Application#deferReadiness}
Modifiers
@public
method boot
boot: () => Promise<this>;
Initialize the application and return a promise that resolves with the
Application
object when the boot process is complete.Run any application 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.
By default, this method is called automatically on "DOM ready"; however, if autoboot is disabled, this is automatically called when the first application instance is created via
visit
.boot {Promise<Application,Error>}
Modifiers
@public
method buildInstance
buildInstance: (options?: EngineInstanceOptions) => ApplicationInstance;
Create an ApplicationInstance for this application.
buildInstance {ApplicationInstance} the application instance
Modifiers
@public
method buildRegistry
static buildRegistry: (namespace: Application) => Registry;
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 theirtarget
andcontrollers
properties all controllers receive the application as theirnamespace
property the application view receives the application controller as itscontroller
property the application view receives the application template as itsdefaultTemplate
propertybuildRegistry
Parameter namespace
the application for which to build the registry {Ember.Registry} the built registry
method deferReadiness
deferReadiness: () => void;
Use this to defer readiness until some condition is true.
Example:
```javascript import Application from '@ember/application';
let App = Application.create();
App.deferReadiness();
fetch('/auth-token') .then(response => response.json()) .then(data => { App.token = data.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.
deferReadiness
Modifiers
@public
method didBecomeReady
didBecomeReady: () => void;
didBecomeReady
method domReady
domReady: () => void;
This is the autoboot flow:
1. Boot the app by calling
this.boot()
2. Create an instance (or use the__deprecatedInstance__
in globals mode) 3. Boot the instance by callinginstance.boot()
4. Invoke theApp.ready()
callback 5. Kick-off routing on the instanceIdeally, this is all we would need to do:
```javascript _autoBoot() { this.boot().then(() => { let instance = (this._globalsMode) ? this.__deprecatedInstance__ : this.buildInstance(); return instance.boot(); }).then((instance) => { App.ready(); instance.startRouting(); }); } ```
Unfortunately, we cannot actually write this because we need to participate in the "synchronous" boot process. While the code above would work fine on the initial boot (i.e. DOM ready), when
App.reset()
is called, we need to boot a new instance synchronously (see the documentation on_bootSync()
for details).Because of this restriction, the actual logic of this method is located inside
didBecomeReady()
.domReady
method init
init: (properties: object | undefined) => void;
method ready
ready: () => this;
Called when the Application has become ready, immediately before routing begins. The call will be delayed until the DOM has become ready.
ready
Modifiers
@public
method reset
reset: () => void;
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 import Application from '@ember/application'; let App;
run(function() { App = 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 import Application from '@ember/application'; let App;
run(function() { App = 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'); }); ```
reset
Modifiers
@public
method visit
visit: (url: string, options: BootOptions) => Promise<unknown>;
Boot a new instance of
ApplicationInstance
for the current application and navigate it to the givenurl
. Returns aPromise
that resolves with the instance when the initial routing and rendering is complete, or rejects with any error that occurred during the boot process.When
autoboot
is disabled, callingvisit
would first cause the application to boot, which runs the application initializers.This method also takes a hash of boot-time configuration options for customizing the instance's behavior. See the documentation on
ApplicationInstance.BootOptions
for details.ApplicationInstance.BootOptions
is an interface class that exists purely to document the available options; you do not need to construct it manually. Simply pass a regular JavaScript object containing of the desired options:```javascript MyApp.visit("/", { location: "none", rootElement: "#container" }); ```
### Supported Scenarios
While the
BootOptions
class exposes a large number of knobs, not all combinations of them are valid; certain incompatible combinations might result in unexpected behavior.For example, booting the instance in the full browser environment while specifying a foreign
document
object (e.g. `{ isBrowser: true, document: iframe.contentDocument }`) does not work correctly today, largely due to Ember's jQuery dependency.Currently, there are three officially supported scenarios/configurations. Usages outside of these scenarios are not guaranteed to work, but please feel free to file bug reports documenting your experience and any issues you encountered to help expand support.
#### Browser Applications (Manual Boot)
The setup is largely similar to how Ember works out-of-the-box. Normally, Ember will boot a default instance for your Application on "DOM ready". However, you can customize this behavior by disabling
autoboot
.For example, this allows you to render a miniture demo of your application into a specific area on your marketing website:
```javascript import MyApp from 'my-app';
$(function() { let App = MyApp.create({ autoboot: false });
let options = { // Override the router's location adapter to prevent it from updating // the URL in the address bar location: 'none',
// Override the default
rootElement
on the app to render into a // specificdiv
on the page rootElement: '#demo' };// Start the app at the special demo URL App.visit('/demo', options); }); ```
Or perhaps you might want to boot two instances of your app on the same page for a split-screen multiplayer experience:
```javascript import MyApp from 'my-app';
$(function() { let App = MyApp.create({ autoboot: false });
let sessionId = MyApp.generateSessionID();
let player1 = App.visit(
/matches/join?name=Player+1&session=${sessionId}
, { rootElement: '#left', location: 'none' }); let player2 = App.visit(/matches/join?name=Player+2&session=${sessionId}
, { rootElement: '#right', location: 'none' });Promise.all([player1, player2]).then(() => { // Both apps have completed the initial render $('#loading').fadeOut(); }); }); ```
Do note that each app instance maintains their own registry/container, so they will run in complete isolation by default.
#### Server-Side Rendering (also known as FastBoot)
This setup allows you to run your Ember app in a server environment using Node.js and render its content into static HTML for SEO purposes.
```javascript const HTMLSerializer = new SimpleDOM.HTMLSerializer(SimpleDOM.voidMap);
function renderURL(url) { let dom = new SimpleDOM.Document(); let rootElement = dom.body; let options = { isBrowser: false, document: dom, rootElement: rootElement };
return MyApp.visit(options).then(instance => { try { return HTMLSerializer.serialize(rootElement.firstChild); } finally { instance.destroy(); } }); } ```
In this scenario, because Ember does not have access to a global
document
object in the Node.js environment, you must provide one explicitly. In practice, in the non-browser environment, the stand-indocument
object only needs to implement a limited subset of the full DOM API. TheSimpleDOM
library is known to work.Since there is no DOM access in the non-browser environment, you must also specify a DOM
Element
object in the samedocument
for therootElement
option (as opposed to a selector string like"body"
).See the documentation on the
isBrowser
,document
androotElement
properties onApplicationInstance.BootOptions
for details.#### Server-Side Resource Discovery
This setup allows you to run the routing layer of your Ember app in a server environment using Node.js and completely disable rendering. This allows you to simulate and discover the resources (i.e. AJAX requests) needed to fulfill a given request and eagerly "push" these resources to the client.
```app/initializers/network-service.js import BrowserNetworkService from 'app/services/network/browser'; import NodeNetworkService from 'app/services/network/node';
// Inject a (hypothetical) service for abstracting all AJAX calls and use // the appropriate implementation on the client/server. This also allows the // server to log all the AJAX calls made during a particular request and use // that for resource-discovery purpose.
export function initialize(application) { if (window) { // browser application.register('service:network', BrowserNetworkService); } else { // node application.register('service:network', NodeNetworkService); } };
export default { name: 'network-service', initialize: initialize }; ```
```app/routes/post.js import Route from '@ember/routing/route'; import { service } from '@ember/service';
// An example of how the (hypothetical) service is used in routes.
export default class IndexRoute extends Route { network;
model(params) { return this.network.fetch(
/api/posts/${params.post_id}.json
); }afterModel(post) { if (post.isExternalContent) { return this.network.fetch(
/api/external/?url=${post.externalURL}
); } else { return post; } } } ``````javascript // Finally, put all the pieces together
function discoverResourcesFor(url) { return MyApp.visit(url, { isBrowser: false, shouldRender: false }).then(instance => { let networkService = instance.lookup('service:network'); return networkService.requests; // => { "/api/posts/123.json": "..." } }); } ```
visit
Parameter url
The initial URL to navigate to
Parameter options
{Promise<ApplicationInstance, Error>}
Modifiers
@public
method waitForDOMReady
waitForDOMReady: () => void;
Automatically kick-off the boot process for the application once the DOM has become ready.
The initialization itself is scheduled on the actions queue which ensures that code-loading finishes before booting.
If you are asynchronously loading code, you should call
deferReadiness()
to defer booting, and then calladvanceReadiness()
once all of your code has finished loading.waitForDOMReady
method willDestroy
willDestroy: () => void;
namespace @ember/application/instance
module '@ember/application/instance' {}
class ApplicationInstance
class ApplicationInstance extends EngineInstance {}
The
ApplicationInstance
encapsulates all of the stateful aspects of a runningApplication
.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.ApplicationInstance EngineInstance
Modifiers
@public
property application
application: Application;
The
Application
for which this is an instance.{Application} application
property customEvents
customEvents: Record<string, string>;
property rootElement
rootElement: any;
The root DOM element of the Application as an element or a CSS selector.
{String|DOMElement} rootElement
property router
readonly router: Router;
method didCreateRootView
didCreateRootView: (view: ViewMixin) => void;
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.
Parameter view
the root-most view
Deprecated
method getURL
getURL: () => string;
Returns the current URL of the app instance. This is useful when your app does not update the browsers URL bar (i.e. it uses the
'none'
location adapter).{String} the current URL
Modifiers
@public
method handleURL
handleURL: (url: string) => any;
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.
Parameter url
the URL the router should route to
method init
init: (properties: object | undefined) => void;
method setupEventDispatcher
setupEventDispatcher: () => EventDispatcher;
method setupRegistry
static setupRegistry: ( registry: Registry, options?: BootOptions | _BootOptions) => void;
setupRegistry
Parameter registry
Parameter options
method setupRouter
setupRouter: () => void;
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.This is commonly used in order to confirm things that rely on the router are functioning properly from tests that are primarily rendering related.
For example, from within [ember-qunit](https://github.com/emberjs/ember-qunit)'s
setupRenderingTest
callingthis.owner.setupRouter()
would allow that rendering test to confirm that any<LinkTo></LinkTo>
's that are rendered have the correct URL.Modifiers
@public
method startRouting
startRouting: () => void;
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.
method visit
visit: (url: string) => any;
Navigate the instance to a particular URL. This is useful in tests, for example, or to tell the app to start at a particular URL. This method returns a promise that resolves with the app instance when the transition is complete, or rejects if the transition was aborted due to an error.
Parameter url
the destination URL {Promise}
Modifiers
@public
method willDestroy
willDestroy: () => void;
namespace @ember/application/lib/lazy_load
module '@ember/application/lib/lazy_load' {}
function onLoad
onLoad: (name: string, callback: (obj: any) => void) => void;
Detects when a specific package of Ember (e.g. 'Application') has fully loaded and is available for extension.
The provided
callback
will be called with thename
passed resolved from a string into the object:``` javascript import { onLoad } from '@ember/application';
onLoad('Ember.Application' function(hbars) { hbars.registerHelper(...); }); ```
onLoad @ember/application
Parameter name
name of hook
Parameter callback
callback to be called
function runLoadHooks
runLoadHooks: (name: string, object: unknown) => void;
Called when an Ember.js package (e.g Application) has finished loading. Triggers any callbacks registered for this event.
runLoadHooks @ember/application
Parameter name
name of hook
Parameter object
object to pass to callbacks
namespace @ember/application/namespace
module '@ember/application/namespace' {}
class Namespace
class Namespace extends EmberObject {}
A Namespace is an object usually used to contain other objects or methods such as an application or framework. Create a namespace anytime you want to define one of these new containers.
# Example Usage
```javascript MyFramework = Ember.Namespace.create({ VERSION: '1.0.0' }); ```
Namespace EmberObject
Modifiers
@public
property byName
static byName: (name: string) => Namespace;
property isNamespace
isNamespace: boolean;
property NAMESPACES
static NAMESPACES: Namespace[];
property NAMESPACES_BY_ID
static NAMESPACES_BY_ID: { [name: string]: Namespace };
property processAll
static processAll: () => void;
method destroy
destroy: () => this;
method init
init: (properties: object | undefined) => void;
method nameClasses
nameClasses: () => void;
method toString
toString: () => string;
namespace @ember/array
module '@ember/array' {}
variable EmberArray
const EmberArray: Mixin;
variable MutableArray
const MutableArray: Mixin;
variable NativeArray
let NativeArray: Mixin;
function A
A: <T>(arr?: T[]) => NativeArray<T>;
function isArray
isArray: (obj: unknown) => obj is EmberArray<unknown> | ArrayLike<unknown>;
Returns true if the passed object is an array or Array-like.
Objects are considered Array-like if any of the following are true:
- the object is a native Array - the object has an objectAt property - the object is an Object, and has a length property
Unlike
typeOf
this method returns true even if the passed object is not formally an array but appears to be array-like (i.e. implementsArray
)```javascript import { isArray } from '@ember/array'; import ArrayProxy from '@ember/array/proxy';
isArray(); // false isArray([]); // true isArray(ArrayProxy.create({ content: [] })); // true ```
isArray @ember/array
Parameter obj
The object to test {Boolean} true if the passed object is an array or Array-like
Modifiers
@public
function makeArray
makeArray: <T, TT>( obj: T) => T extends TT[] ? T : T extends null | undefined ? [] : [T];
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 object is
null
orundefined
, it will return an empty array.```javascript import { makeArray } from '@ember/array'; import ArrayProxy from '@ember/array/proxy';
makeArray(); // [] makeArray(null); // [] makeArray(undefined); // [] makeArray('lindsay'); // ['lindsay'] makeArray([1, 2, 42]); // [1, 2, 42]
let proxy = ArrayProxy.create({ content: [] });
makeArray(proxy) === proxy; // false ```
makeArray @ember/array
Parameter obj
the object {Array}
function removeAt
removeAt: <T, A extends T[] | MutableArray<T>>( array: A, index: number, len?: number) => A;
function uniqBy
uniqBy: <T>( array: T[] | EmberArray<T>, keyOrFunc?: string | ((item: T) => unknown)) => T[] | EmberArray<T>;
interface EmberArray
interface EmberArray<T> extends Enumerable {}
This mixin implements Observer-friendly Array-like behavior. It is not a concrete implementation, but it can be used up by other classes that want to appear like arrays.
For example, ArrayProxy is a concrete class that can be instantiated to implement array-like behavior. This class uses the Array Mixin by way of the MutableArray mixin, which allows observable changes to be made to the underlying array.
This mixin defines methods specifically for collections that provide index-ordered access to their contents. When you are designing code that needs to accept any kind of Array-like object, you should use these methods instead of Array primitives because these will properly notify observers of changes to the array.
Although these methods are efficient, they do add a layer of indirection to your application so it is a good idea to use them only when you need the flexibility of using both true JavaScript arrays and "virtual" arrays such as controllers and collections.
You can use the methods defined in this module to access and modify array contents in an observable-friendly way. You can also be notified whenever the membership of an array changes by using
.observes('myArray.[]')
.To support
EmberArray
in your own class, you must override two primitives to use it:length()
andobjectAt()
.EmberArray Enumerable Ember 0.9.0
Modifiers
@public
property firstObject
firstObject: T | undefined;
The first object in the array, or
undefined
if the array is empty.```javascript let vowels = ['a', 'e', 'i', 'o', 'u']; vowels.firstObject; // 'a'
vowels.shiftObject(); vowels.firstObject; // 'e'
vowels.reverseObjects(); vowels.firstObject; // 'u'
vowels.clear(); vowels.firstObject; // undefined ```
firstObject {Object | undefined} The first object in the array
Modifiers
@public
property lastObject
lastObject: T | undefined;
The last object in the array, or
undefined
if the array is empty.lastObject {Object | undefined} The last object in the array
Modifiers
@public
property length
length: number;
__Required.__ You must implement this method to apply this mixin.
Your array must support the
length
property. Your replace methods should set this property whenever it changes.{Number} length
Modifiers
@public
method any
any: <Target = void>( callback: (this: Target, item: T, index: number, arr: this) => unknown, target?: Target) => boolean;
The any() method executes the callback function once for each element present in the array until it finds the one where callback returns a truthy value (i.e.
true
). If such an element is found, any() immediately returns true. Otherwise, any() returns false.```javascript function(item, index, array); ```
-
item
is the current item in the iteration. -index
is the current index in the iteration. -array
is the array object itself.Note that in addition to a callback, you can also pass an optional target object that will be set as
this
on the context. It can be a good way to give your iterator function access to an object in cases where an ES6 arrow function would not be appropriate.Usage Example:
```javascript let includesManager = people.any(this.findPersonInManagersList, this);
let includesStockHolder = people.any(person => { return this.findPersonInStockHoldersList(person) });
if (includesManager || includesStockHolder) { Paychecks.addBiggerBonus(); } ```
any
Parameter callback
The callback to execute
Parameter target
The target object to use {Boolean}
true
if the passed function returnstrue
for any itemModifiers
@public
method compact
compact: () => NativeArray<NonNullable<T>>;
Returns a copy of the array with all
null
andundefined
elements removed.```javascript let arr = ['a', null, 'c', undefined]; arr.compact(); // ['a', 'c'] ```
compact {Array} the array without null and undefined elements.
Modifiers
@public
method every
every: <Target = void>( callback: (this: Target, item: T, index: number, arr: this) => unknown, target?: Target) => boolean;
Returns
true
if the passed function returns true for every item in the enumeration. This corresponds with theArray.prototype.every()
method defined in ES5.The callback method should have the following signature:
```javascript function(item, index, array); ```
-
item
is the current item in the iteration. -index
is the current index in the iteration. -array
is the array itself.All params are optional. The method should return
true
orfalse
.Note that in addition to a callback, you can also pass an optional target object that will be set as
this
on the context. This is a good way to give your iterator function access to the current object.Usage example:
```javascript function isAdult(person) { return person.age > 18; };
const people = Ember.A([{ name: 'John', age: 24 }, { name: 'Joan', age: 45 }]); const areAllAdults = people.every(isAdult); ```
every
Parameter callback
The callback to execute
Parameter target
The target object to use {Boolean}
Modifiers
@public
method filter
filter: <Target>( callback: (this: Target, item: T, index: number, arr: this) => unknown, target?: Target) => NativeArray<T>;
Returns a new array with all of the items in the enumeration that the provided callback function returns true for. This method corresponds to [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter).
The callback method should have the following signature:
```javascript function(item, index, array); ```
-
item
is the current item in the iteration. -index
is the current index in the iteration. -array
is the array itself.All parameters are optional. The function should return
true
to include the item in the results, andfalse
otherwise.Example:
```javascript function isAdult(person) { return person.age > 18; };
let people = Ember.A([{ name: 'John', age: 14 }, { name: 'Joan', age: 45 }]);
people.filter(isAdult); // returns [{ name: 'Joan', age: 45 }]; ```
Note that in addition to a callback, you can pass an optional target object that will be set as
this
on the context. This is a good way to give your iterator function access to the current object. For example:```javascript function isAdultAndEngineer(person) { return person.age > 18 && this.engineering; }
class AdultsCollection { engineering = false;
constructor(opts = {}) { super(...arguments);
this.engineering = opts.engineering; this.people = Ember.A([{ name: 'John', age: 14 }, { name: 'Joan', age: 45 }]); } }
let collection = new AdultsCollection({ engineering: true }); collection.people.filter(isAdultAndEngineer, { target: collection }); ```
filter
Parameter callback
The callback to execute
Parameter target
The target object to use {Array} A filtered array.
Modifiers
@public
method filterBy
filterBy: (key: string, value?: unknown) => NativeArray<T>;
Filters the array by the property and an optional value. If a value is given, it returns the items that have said value for the property. If not, it returns all the items that have a truthy value for the property.
Example Usage:
```javascript let things = Ember.A([{ food: 'apple', isFruit: true }, { food: 'beans', isFruit: false }]);
things.filterBy('food', 'beans'); // [{ food: 'beans', isFruit: false }] things.filterBy('isFruit'); // [{ food: 'apple', isFruit: true }] ```
filterBy
Parameter key
the property to test
Parameter value
optional value to test against. {Array} filtered array
Modifiers
@public
method find
find: { <S extends T, Target = void>( predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: Target ): S | undefined; <Target = void>( callback: (this: Target, item: T, index: number, arr: this) => unknown, target?: Target ): T;};
Returns the first item in the array for which the callback returns true. This method is similar to the
find()
method defined in ECMAScript 2015.The callback method you provide should have the following signature (all parameters are optional):
```javascript function(item, index, array); ```
-
item
is the current item in the iteration. -index
is the current index in the iteration. -array
is the array itself.It should return the
true
to include the item in the results,false
otherwise.Note that in addition to a callback, you can also pass an optional target object that will be set as
this
on the context. This is a good way to give your iterator function access to the current object.Example Usage:
```javascript let users = [ { id: 1, name: 'Yehuda' }, { id: 2, name: 'Tom' }, { id: 3, name: 'Melanie' }, { id: 4, name: 'Leah' } ];
users.find((user) => user.name == 'Tom'); // [{ id: 2, name: 'Tom' }] users.find(({ id }) => id == 3); // [{ id: 3, name: 'Melanie' }] ```
find
Parameter callback
The callback to execute
Parameter target
The target object to use {Object} Found item or
undefined
.Modifiers
@public
method findBy
findBy: { <K extends keyof T>(key: K, value?: T[K]): T | undefined; (key: string, value?: unknown): T;};
Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to
true
.This method works much like the more generic
find()
method.Usage Example:
```javascript let users = [ { id: 1, name: 'Yehuda', isTom: false }, { id: 2, name: 'Tom', isTom: true }, { id: 3, name: 'Melanie', isTom: false }, { id: 4, name: 'Leah', isTom: false } ];
users.findBy('id', 4); // { id: 4, name: 'Leah', isTom: false } users.findBy('name', 'Melanie'); // { id: 3, name: 'Melanie', isTom: false } users.findBy('isTom'); // { id: 2, name: 'Tom', isTom: true } ```
findBy
Parameter key
the property to test
Parameter value
optional value to test against. {Object} found item or
undefined
Modifiers
@public
method forEach
forEach: <Target>( callback: (this: Target, item: T, index: number, arr: this) => void, target?: Target) => this;
Iterates through the array, calling the passed function on each item. This method corresponds to the
forEach()
method defined in JavaScript 1.6.The callback method you provide should have the following signature (all parameters are optional):
```javascript function(item, index, array); ```
-
item
is the current item in the iteration. -index
is the current index in the iteration. -array
is the array itself.Note that in addition to a callback, you can also pass an optional target object that will be set as
this
on the context. This is a good way to give your iterator function access to the current object.Example Usage:
```javascript let foods = [ { name: 'apple', eaten: false }, { name: 'banana', eaten: false }, { name: 'carrot', eaten: false } ];
foods.forEach((food) => food.eaten = true);
let output = ''; foods.forEach((item, index, array) => output +=
${index + 1}/${array.length} ${item.name}\n
; ); console.log(output); // 1/3 apple // 2/3 banana // 3/3 carrot ```forEach
Parameter callback
The callback to execute
Parameter target
The target object to use {Object} receiver
Modifiers
@public
method getEach
getEach: <K extends keyof T>(key: K) => NativeArray<T[K]>;
Alias for
mapBy
.Returns the value of the named property on all items in the enumeration.
```javascript let people = [{name: 'Joe'}, {name: 'Matt'}];
people.getEach('name'); // ['Joe', 'Matt'];
people.getEach('nonexistentProperty'); // [undefined, undefined]; ```
getEach
Parameter key
name of the property {Array} The mapped array.
Modifiers
@public
method includes
includes: (object: T, startAt?: number) => boolean;
Used to determine if the array contains the passed object. Returns
true
if found,false
otherwise.The optional
startAt
argument can be used to pass a starting index to search from, effectively slicing the searchable portion of the array. If it's negative it will add the array length to the startAt value passed in as the index to search from. If less than or equal to-1 * array.length
the entire array is searched.This method has the same behavior of JavaScript's [Array.includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes).
```javascript [1, 2, 3].includes(2); // true [1, 2, 3].includes(4); // false [1, 2, 3].includes(3, 2); // true [1, 2, 3].includes(3, 3); // false [1, 2, 3].includes(3, -1); // true [1, 2, 3].includes(1, -1); // false [1, 2, 3].includes(1, -4); // true [1, 2, NaN].includes(NaN); // true ```
includes
Parameter object
The object to search for.
Parameter startAt
optional starting location to search, default 0 {Boolean}
true
if object is found in the array.Modifiers
@public
method indexOf
indexOf: (object: T, startAt?: number) => number;
Used to determine the passed object's first occurrence in the array. Returns the index if found, -1 if no match is found.
The optional
startAt
argument can be used to pass a starting index to search from, effectively slicing the searchable portion of the array. If it's negative it will add the array length to the startAt value passed in as the index to search from. If less than or equal to-1 * array.length
the entire array is searched.```javascript let arr = ['a', 'b', 'c', 'd', 'a'];
arr.indexOf('a'); // 0 arr.indexOf('z'); // -1 arr.indexOf('a', 2); // 4 arr.indexOf('a', -1); // 4, equivalent to indexOf('a', 4) arr.indexOf('a', -100); // 0, searches entire array arr.indexOf('b', 3); // -1 arr.indexOf('a', 100); // -1
let people = [{ name: 'Zoey' }, { name: 'Bob' }] let newPerson = { name: 'Tom' }; people = [newPerson, ...people, newPerson];
people.indexOf(newPerson); // 0 people.indexOf(newPerson, 1); // 3 people.indexOf(newPerson, -4); // 0 people.indexOf(newPerson, 10); // -1 ```
indexOf
Parameter object
the item to search for
Parameter startAt
optional starting location to search, default 0 {Number} index or -1 if not found
Modifiers
@public
method invoke
invoke: <M extends keyof MethodsOf<T>>( methodName: M, ...args: MethodParams<T, M>) => NativeArray<MethodReturns<T, M>>;
Invokes the named method on every object in the receiver that implements it. This method corresponds to the implementation in Prototype 1.6.
```javascript class Person { name = null;
constructor(name) { this.name = name; }
greet(prefix='Hello') { return
${prefix} ${this.name}
; } }let people = [new Person('Joe'), new Person('Matt')];
people.invoke('greet'); // ['Hello Joe', 'Hello Matt'] people.invoke('greet', 'Bonjour'); // ['Bonjour Joe', 'Bonjour Matt'] ```
invoke
Parameter methodName
the name of the method
Parameter args
optional arguments to pass as well. {Array} return values from calling invoke.
Modifiers
@public
method isAny
isAny: { <K extends keyof T>(key: K, value?: T[K]): boolean; (key: string, value?: unknown): boolean;};
Returns
true
if the passed property resolves to the value of the second argument for any item in the array. This method is often simpler/faster than using a callback.Example usage:
```javascript const food = [ { food: 'apple', isFruit: true }, { food: 'bread', isFruit: false }, { food: 'banana', isFruit: true } ];
food.isAny('isFruit'); // true ```
isAny
Parameter key
the property to test
Parameter value
optional value to test against. Defaults to
true
{Boolean} 1.3.0Modifiers
@public
method isEvery
isEvery: { <K extends keyof T>(key: K, value?: T[K]): boolean; (key: string, value?: unknown): boolean;};
Returns
true
if the passed property resolves to the value of the second argument for all items in the array. This method is often simpler/faster than using a callback.Note that like the native
Array.every
,isEvery
will return true when called on any empty array. ```javascript class Language { constructor(name, isProgrammingLanguage) { this.name = name; this.programmingLanguage = isProgrammingLanguage; } }const compiledLanguages = [ new Language('Java', true), new Language('Go', true), new Language('Rust', true) ]
const languagesKnownByMe = [ new Language('Javascript', true), new Language('English', false), new Language('Ruby', true) ]
compiledLanguages.isEvery('programmingLanguage'); // true languagesKnownByMe.isEvery('programmingLanguage'); // false ```
isEvery
Parameter key
the property to test
Parameter value
optional value to test against. Defaults to
true
{Boolean} 1.3.0Modifiers
@public
method lastIndexOf
lastIndexOf: (object: T, startAt?: number) => number;
Returns the index of the given
object
's last occurrence.- If no
startAt
argument is given, the search starts from the last position. - If it's greater than or equal to the length of the array, the search starts from the last position. - If it's negative, it is taken as the offset from the end of the array i.e.startAt + array.length
. - If it's any other positive number, will search backwards from that index of the array.Returns -1 if no match is found.
```javascript let arr = ['a', 'b', 'c', 'd', 'a'];
arr.lastIndexOf('a'); // 4 arr.lastIndexOf('z'); // -1 arr.lastIndexOf('a', 2); // 0 arr.lastIndexOf('a', -1); // 4 arr.lastIndexOf('a', -3); // 0 arr.lastIndexOf('b', 3); // 1 arr.lastIndexOf('a', 100); // 4 ```
lastIndexOf
Parameter object
the item to search for
Parameter startAt
optional starting location to search from backwards, defaults to
(array.length - 1)
{Number} The last index of theobject
in the array or -1 if not foundModifiers
@public
method map
map: <U, Target>( callback: (this: Target, item: T, index: number, arr: this) => U, target?: Target) => NativeArray<U>;
Maps all of the items in the enumeration to another value, returning a new array. This method corresponds to
map()
defined in JavaScript 1.6.The callback method you provide should have the following signature (all parameters are optional):
```javascript function(item, index, array); let arr = [1, 2, 3, 4, 5, 6];
arr.map(element => element * element); // [1, 4, 9, 16, 25, 36];
arr.map((element, index) => element + index); // [1, 3, 5, 7, 9, 11]; ```
-
item
is the current item in the iteration. -index
is the current index in the iteration. -array
is the array itself.It should return the mapped value.
Note that in addition to a callback, you can also pass an optional target object that will be set as
this
on the context. This is a good way to give your iterator function access to the current object.map
Parameter callback
The callback to execute
Parameter target
The target object to use {Array} The mapped array.
Modifiers
@public
method mapBy
mapBy: { <K extends keyof T>(key: K): NativeArray<T[K]>; (key: string): NativeArray<unknown>;};
Similar to map, this specialized function returns the value of the named property on all items in the enumeration.
```javascript let people = [{name: 'Joe'}, {name: 'Matt'}];
people.mapBy('name'); // ['Joe', 'Matt'];
people.mapBy('unknownProperty'); // [undefined, undefined]; ```
mapBy
Parameter key
name of the property {Array} The mapped array.
Modifiers
@public
method objectAt
objectAt: (idx: number) => T | undefined;
Returns the object at the given
index
. If the givenindex
is negative or is greater or equal than the array length, returnsundefined
.This is one of the primitives you must implement to support
EmberArray
. If your object supports retrieving the value of an array item usingget()
(i.e.myArray.get(0)
), then you do not need to implement this method yourself.```javascript let arr = ['a', 'b', 'c', 'd'];
arr.objectAt(0); // 'a' arr.objectAt(3); // 'd' arr.objectAt(-1); // undefined arr.objectAt(4); // undefined arr.objectAt(5); // undefined ```
objectAt
Parameter idx
The index of the item to return. {*} item at index or undefined
Modifiers
@public
method objectsAt
objectsAt: (indexes: number[]) => Array<T | undefined>;
This returns the objects at the specified indexes, using
objectAt
.```javascript let arr = ['a', 'b', 'c', 'd'];
arr.objectsAt([0, 1, 2]); // ['a', 'b', 'c'] arr.objectsAt([2, 3, 4]); // ['c', 'd', undefined] ```
objectsAt
Parameter indexes
An array of indexes of items to return. {Array}
Modifiers
@public
method reduce
reduce: <V>( callback: (summation: V, current: T, index: number, arr: this) => V, initialValue?: V) => V;
This will combine the values of the array into a single value. It is a useful way to collect a summary value from an array. This corresponds to the
reduce()
method defined in JavaScript 1.8.The callback method you provide should have the following signature (all parameters are optional):
```javascript function(previousValue, item, index, array); ```
-
previousValue
is the value returned by the last call to the iterator. -item
is the current item in the iteration. -index
is the current index in the iteration. -array
is the array itself.Return the new cumulative value.
In addition to the callback you can also pass an
initialValue
. An error will be raised if you do not pass an initial value and the enumerator is empty.Note that unlike the other methods, this method does not allow you to pass a target object to set as this for the callback. It's part of the spec. Sorry.
Example Usage:
```javascript let numbers = [1, 2, 3, 4, 5];
numbers.reduce(function(summation, current) { return summation + current; }); // 15 (1 + 2 + 3 + 4 + 5)
numbers.reduce(function(summation, current) { return summation + current; }, -15); // 0 (-15 + 1 + 2 + 3 + 4 + 5)
let binaryValues = [true, false, false];
binaryValues.reduce(function(truthValue, current) { return truthValue && current; }); // false (true && false && false) ```
reduce
Parameter callback
The callback to execute
Parameter initialValue
Initial value for the reduce {Object} The reduced value.
Modifiers
@public
method reject
reject: <Target>( callback: (this: Target, item: T, index: number, arr: this) => unknown, target?: Target) => NativeArray<T>;
Returns an array with all of the items in the enumeration where the passed function returns false. This method is the inverse of filter().
The callback method you provide should have the following signature (all parameters are optional):
```javascript function(item, index, array); ```
- *item* is the current item in the iteration. - *index* is the current index in the iteration - *array* is the array itself.
It should return a falsey value to include the item in the results.
Note that in addition to a callback, you can also pass an optional target object that will be set as "this" on the context. This is a good way to give your iterator function access to the current object.
Example Usage:
```javascript const food = [ { food: 'apple', isFruit: true }, { food: 'bread', isFruit: false }, { food: 'banana', isFruit: true } ]; const nonFruits = food.reject(function(thing) { return thing.isFruit; }); // [{food: 'bread', isFruit: false}] ```
reject
Parameter callback
The callback to execute
Parameter target
The target object to use {Array} A rejected array.
Modifiers
@public
method rejectBy
rejectBy: (key: string, value?: unknown) => NativeArray<T>;
Returns an array with the items that do not have truthy values for the provided key. You can pass an optional second argument with a target value to reject for the key. Otherwise this will reject objects where the provided property evaluates to false.
Example Usage:
```javascript let food = [ { name: "apple", isFruit: true }, { name: "carrot", isFruit: false }, { name: "bread", isFruit: false }, ]; food.rejectBy('isFruit'); // [{ name: "carrot", isFruit: false }, { name: "bread", isFruit: false }] food.rejectBy('name', 'carrot'); // [{ name: "apple", isFruit: true }}, { name: "bread", isFruit: false }] ```
rejectBy
Parameter key
the property to test
Parameter value
optional value to test against. {Array} rejected array
Modifiers
@public
method setEach
setEach: <K extends keyof T>(key: K, value: T[K]) => this;
Sets the value on the named property for each member. This is more ergonomic than using other methods defined on this helper. If the object implements Observable, the value will be changed to
set(),
otherwise it will be set directly.null
objects are skipped.```javascript let people = [{name: 'Joe'}, {name: 'Matt'}];
people.setEach('zipCode', '10011'); // [{name: 'Joe', zipCode: '10011'}, {name: 'Matt', zipCode: '10011'}]; ```
setEach
Parameter key
The key to set
Parameter value
The object to set {Object} receiver
Modifiers
@public
method slice
slice: (beginIndex?: number, endIndex?: number) => NativeArray<T>;
Returns a new array that is a slice of the receiver. This implementation uses the observable array methods to retrieve the objects for the new slice.
```javascript let arr = ['red', 'green', 'blue'];
arr.slice(0); // ['red', 'green', 'blue'] arr.slice(0, 2); // ['red', 'green'] arr.slice(1, 100); // ['green', 'blue'] ```
slice
Parameter beginIndex
(Optional) index to begin slicing from.
Parameter endIndex
(Optional) index to end the slice at (but not included). {Array} New array with specified slice
Modifiers
@public
method sortBy
sortBy: (...keys: string[]) => T[];
Sorts the array by the keys specified in the argument.
You may provide multiple arguments to sort by multiple properties.
```javascript let colors = [ { name: 'red', weight: 500 }, { name: 'green', weight: 600 }, { name: 'blue', weight: 500 } ];
colors.sortBy('name'); // [{name: 'blue', weight: 500}, {name: 'green', weight: 600}, {name: 'red', weight: 500}]
colors.sortBy('weight', 'name'); // [{name: 'blue', weight: 500}, {name: 'red', weight: 500}, {name: 'green', weight: 600}] ``` sortBy
Parameter property
name(s) to sort on {Array} The sorted array. 1.2.0
Modifiers
@public
method toArray
toArray: () => T[];
Simply converts the object into a genuine array. The order is not guaranteed. Corresponds to the method implemented by Prototype.
toArray {Array} the object as an array.
Modifiers
@public
method uniq
uniq: () => NativeArray<T>;
Returns a new array that contains only unique values. The default implementation returns an array regardless of the receiver type.
```javascript let arr = ['a', 'a', 'b', 'b']; arr.uniq(); // ['a', 'b'] ```
This only works on primitive data types, e.g. Strings, Numbers, etc.
uniq {EmberArray}
Modifiers
@public
method uniqBy
uniqBy: { (key: string): NativeArray<T>; (callback: (value: T) => unknown): NativeArray<T>;};
Returns a new array that contains only items containing a unique property value. The default implementation returns an array regardless of the receiver type.
```javascript let arr = [{ value: 'a' }, { value: 'a' }, { value: 'b' }, { value: 'b' }]; arr.uniqBy('value'); // [{ value: 'a' }, { value: 'b' }]
let arr = [2.2, 2.1, 3.2, 3.3]; arr.uniqBy(Math.floor); // [2.2, 3.2]; ```
uniqBy
Parameter key
{EmberArray}
Modifiers
@public
method without
without: (value: T) => NativeArray<T>;
Returns a new array that excludes the passed value. The default implementation returns an array regardless of the receiver type. If the receiver does not contain the value it returns the original array.
```javascript let arr = ['a', 'b', 'a', 'c']; arr.without('a'); // ['b', 'c'] ```
without
Parameter value
{EmberArray}
Modifiers
@public
index signature
get '[]'(): this;
This is the handler for the special array content property. If you get this property, it will return this. If you set this property to a new array, it will replace the current content.
```javascript let peopleToMoon = ['Armstrong', 'Aldrin'];
peopleToMoon.get('[]'); // ['Armstrong', 'Aldrin']
peopleToMoon.set('[]', ['Collins']); // ['Collins'] peopleToMoon.get('[]'); // ['Collins'] ```
[] this
Modifiers
@public
index signature
set '[]'(newValue: T[] | EmberArray<T>);
interface MutableArray
interface MutableArray<T> extends EmberArray<T>, MutableEnumerable {}
This mixin defines the API for modifying array-like objects. These methods can be applied only to a collection that keeps its items in an ordered set. It builds upon the Array mixin and adds methods to modify the array. One concrete implementations of this class include ArrayProxy.
It is important to use the methods in this class to modify arrays so that changes are observable. This allows the binding system in Ember to function correctly.
Note that an Array can change even if it does not implement this mixin. For example, one might implement a SparseArray that cannot be directly modified, but if its underlying enumerable changes, it will change also.
MutableArray EmberArray MutableEnumerable
Modifiers
@public
method addObject
addObject: (obj: T) => this;
Push the object onto the end of the array if it is not already present in the array.
```javascript let cities = ['Chicago', 'Berlin'];
cities.addObject('Lima'); // ['Chicago', 'Berlin', 'Lima'] cities.addObject('Berlin'); // ['Chicago', 'Berlin', 'Lima'] ```
addObject
Parameter obj
object to add, if not already present {EmberArray} receiver
Modifiers
@public
method addObjects
addObjects: (objects: T[]) => this;
Adds each object in the passed array to the receiver.
addObjects
Parameter objects
the objects to add. {EmberArray} receiver
Modifiers
@public
method clear
clear: () => this;
Remove all elements from the array. This is useful if you want to reuse an existing array without having to recreate it.
```javascript let colors = ['red', 'green', 'blue'];
colors.length; // 3 colors.clear(); // [] colors.length; // 0 ```
clear {Array} An empty Array.
Modifiers
@public
method insertAt
insertAt: (idx: number, object: T) => this;
This will use the primitive
replace()
method to insert an object at the specified index.```javascript let colors = ['red', 'green', 'blue'];
colors.insertAt(2, 'yellow'); // ['red', 'green', 'yellow', 'blue'] colors.insertAt(5, 'orange'); // Error: Index out of range ```
insertAt
Parameter idx
index of insert the object at.
Parameter object
object to insert {EmberArray} receiver
Modifiers
@public
method popObject
popObject: () => T | null | undefined;
Pop object from array or nil if none are left. Works just like
pop()
but it is KVO-compliant.```javascript let colors = ['red', 'green', 'blue'];
colors.popObject(); // 'blue' console.log(colors); // ['red', 'green'] ```
popObject object
Modifiers
@public
method pushObject
pushObject: (obj: T) => T;
Push the object onto the end of the array. Works just like
push()
but it is KVO-compliant.```javascript let colors = ['red', 'green'];
colors.pushObject('black'); // ['red', 'green', 'black'] colors.pushObject(['yellow']); // ['red', 'green', ['yellow']] ```
pushObject
Parameter obj
object to push object same object passed as a param
Modifiers
@public
method pushObjects
pushObjects: (objects: T[]) => this;
Add the objects in the passed array to the end of the array. Defers notifying observers of the change until all objects are added.
```javascript let colors = ['red'];
colors.pushObjects(['yellow', 'orange']); // ['red', 'yellow', 'orange'] ```
pushObjects
Parameter objects
the objects to add {MutableArray} receiver
Modifiers
@public
method removeAt
removeAt: (start: number, len?: number) => this;
Remove an object at the specified index using the
replace()
primitive method. You can pass either a single index, or a start and a length.If you pass a start and length that is beyond the length this method will throw an assertion.
```javascript let colors = ['red', 'green', 'blue', 'yellow', 'orange'];
colors.removeAt(0); // ['green', 'blue', 'yellow', 'orange'] colors.removeAt(2, 2); // ['green', 'blue'] colors.removeAt(4, 2); // Error: Index out of range ```
removeAt
Parameter start
index, start of range
Parameter len
length of passing range {EmberArray} receiver
Modifiers
@public
method removeObject
removeObject: (object: T) => this;
Remove all occurrences of an object in the array.
```javascript let cities = ['Chicago', 'Berlin', 'Lima', 'Chicago'];
cities.removeObject('Chicago'); // ['Berlin', 'Lima'] cities.removeObject('Lima'); // ['Berlin'] cities.removeObject('Tokyo') // ['Berlin'] ```
removeObject
Parameter obj
object to remove {EmberArray} receiver
Modifiers
@public
method removeObjects
removeObjects: (objects: T[]) => this;
Removes each object in the passed array from the receiver.
removeObjects
Parameter objects
the objects to remove {EmberArray} receiver
Modifiers
@public
method replace
replace: (idx: number, amt: number, objects?: readonly T[]) => void;
__Required.__ You must implement this method to apply this mixin.
This is one of the primitives you must implement to support
Array
. You should replace amt objects started at idx with the objects in the passed array.Note that this method is expected to validate the type(s) of objects that it expects.
replace
Parameter idx
Starting index in the array to replace. If idx >= length, then append to the end of the array.
Parameter amt
Number of elements that should be removed from the array, starting at *idx*.
Parameter objects
An optional array of zero or more objects that should be inserted into the array at *idx*
Modifiers
@public
method reverseObjects
reverseObjects: () => this;
Reverse objects in the array. Works just like
reverse()
but it is KVO-compliant.reverseObjects {EmberArray} receiver
Modifiers
@public
method setObjects
setObjects: (object: T[]) => this;
Replace all the receiver's content with content of the argument. If argument is an empty array receiver will be cleared.
```javascript let colors = ['red', 'green', 'blue'];
colors.setObjects(['black', 'white']); // ['black', 'white'] colors.setObjects([]); // [] ```
setObjects
Parameter objects
array whose content will be used for replacing the content of the receiver {EmberArray} receiver with the new content
Modifiers
@public
method shiftObject
shiftObject: () => T | null | undefined;
Shift an object from start of array or nil if none are left. Works just like
shift()
but it is KVO-compliant.```javascript let colors = ['red', 'green', 'blue'];
colors.shiftObject(); // 'red' console.log(colors); // ['green', 'blue'] ```
shiftObject object
Modifiers
@public
method unshiftObject
unshiftObject: (object: T) => T;
Unshift an object to start of array. Works just like
unshift()
but it is KVO-compliant.```javascript let colors = ['red'];
colors.unshiftObject('yellow'); // ['yellow', 'red'] colors.unshiftObject(['black']); // [['black'], 'yellow', 'red'] ```
unshiftObject
Parameter obj
object to unshift object same object passed as a param
Modifiers
@public
method unshiftObjects
unshiftObjects: (objects: T[]) => this;
Adds the named objects to the beginning of the array. Defers notifying observers until all objects have been added.
```javascript let colors = ['red'];
colors.unshiftObjects(['black', 'white']); // ['black', 'white', 'red'] colors.unshiftObjects('yellow'); // Type Error: 'undefined' is not a function ```
unshiftObjects
Parameter objects
the objects to add {EmberArray} receiver
Modifiers
@public
interface NativeArray
interface NativeArray<T> extends Array<T>, Observable, MutableArrayWithoutNative<T> {}
The NativeArray mixin contains the properties needed to make the native Array support MutableArray and all of its dependent APIs.
Ember.NativeArray MutableArray Observable
Modifiers
@public
type EmberArrayLike
type EmberArrayLike<T> = EmberArray<T> | NativeArray<T>;
namespace @ember/array/-internals
module '@ember/array/-internals' {}
function isEmberArray
isEmberArray: (obj: unknown) => obj is EmberArrayLike<unknown>;
function setEmberArray
setEmberArray: (obj: object) => void;
namespace @ember/array/lib/make-array
module '@ember/array/lib/make-array' {}
function makeArray
makeArray: <T, TT>( obj: T) => T extends TT[] ? T : T extends null | undefined ? [] : [T];
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 object is
null
orundefined
, it will return an empty array.```javascript import { makeArray } from '@ember/array'; import ArrayProxy from '@ember/array/proxy';
makeArray(); // [] makeArray(null); // [] makeArray(undefined); // [] makeArray('lindsay'); // ['lindsay'] makeArray([1, 2, 42]); // [1, 2, 42]
let proxy = ArrayProxy.create({ content: [] });
makeArray(proxy) === proxy; // false ```
makeArray @ember/array
Parameter obj
the object {Array}
namespace @ember/array/make
module '@ember/array/make' {}
function makeArray
makeArray: <T, TT>( obj: T) => T extends TT[] ? T : T extends null | undefined ? [] : [T];
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 object is
null
orundefined
, it will return an empty array.```javascript import { makeArray } from '@ember/array'; import ArrayProxy from '@ember/array/proxy';
makeArray(); // [] makeArray(null); // [] makeArray(undefined); // [] makeArray('lindsay'); // ['lindsay'] makeArray([1, 2, 42]); // [1, 2, 42]
let proxy = ArrayProxy.create({ content: [] });
makeArray(proxy) === proxy; // false ```
makeArray @ember/array
Parameter obj
the object {Array}
namespace @ember/array/mutable
module '@ember/array/mutable' {}
variable MutableArray
const MutableArray: Mixin;
interface MutableArray
interface MutableArray<T> extends EmberArray<T>, MutableEnumerable {}
This mixin defines the API for modifying array-like objects. These methods can be applied only to a collection that keeps its items in an ordered set. It builds upon the Array mixin and adds methods to modify the array. One concrete implementations of this class include ArrayProxy.
It is important to use the methods in this class to modify arrays so that changes are observable. This allows the binding system in Ember to function correctly.
Note that an Array can change even if it does not implement this mixin. For example, one might implement a SparseArray that cannot be directly modified, but if its underlying enumerable changes, it will change also.
MutableArray EmberArray MutableEnumerable
Modifiers
@public
method addObject
addObject: (obj: T) => this;
Push the object onto the end of the array if it is not already present in the array.
```javascript let cities = ['Chicago', 'Berlin'];
cities.addObject('Lima'); // ['Chicago', 'Berlin', 'Lima'] cities.addObject('Berlin'); // ['Chicago', 'Berlin', 'Lima'] ```
addObject
Parameter obj
object to add, if not already present {EmberArray} receiver
Modifiers
@public
method addObjects
addObjects: (objects: T[]) => this;
Adds each object in the passed array to the receiver.
addObjects
Parameter objects
the objects to add. {EmberArray} receiver
Modifiers
@public
method clear
clear: () => this;
Remove all elements from the array. This is useful if you want to reuse an existing array without having to recreate it.
```javascript let colors = ['red', 'green', 'blue'];
colors.length; // 3 colors.clear(); // [] colors.length; // 0 ```
clear {Array} An empty Array.
Modifiers
@public
method insertAt
insertAt: (idx: number, object: T) => this;
This will use the primitive
replace()
method to insert an object at the specified index.```javascript let colors = ['red', 'green', 'blue'];
colors.insertAt(2, 'yellow'); // ['red', 'green', 'yellow', 'blue'] colors.insertAt(5, 'orange'); // Error: Index out of range ```
insertAt
Parameter idx
index of insert the object at.
Parameter object
object to insert {EmberArray} receiver
Modifiers
@public
method popObject
popObject: () => T | null | undefined;
Pop object from array or nil if none are left. Works just like
pop()
but it is KVO-compliant.```javascript let colors = ['red', 'green', 'blue'];
colors.popObject(); // 'blue' console.log(colors); // ['red', 'green'] ```
popObject object
Modifiers
@public
method pushObject
pushObject: (obj: T) => T;
Push the object onto the end of the array. Works just like
push()
but it is KVO-compliant.```javascript let colors = ['red', 'green'];
colors.pushObject('black'); // ['red', 'green', 'black'] colors.pushObject(['yellow']); // ['red', 'green', ['yellow']] ```
pushObject
Parameter obj
object to push object same object passed as a param
Modifiers
@public
method pushObjects
pushObjects: (objects: T[]) => this;
Add the objects in the passed array to the end of the array. Defers notifying observers of the change until all objects are added.
```javascript let colors = ['red'];
colors.pushObjects(['yellow', 'orange']); // ['red', 'yellow', 'orange'] ```
pushObjects
Parameter objects
the objects to add {MutableArray} receiver
Modifiers
@public
method removeAt
removeAt: (start: number, len?: number) => this;
Remove an object at the specified index using the
replace()
primitive method. You can pass either a single index, or a start and a length.If you pass a start and length that is beyond the length this method will throw an assertion.
```javascript let colors = ['red', 'green', 'blue', 'yellow', 'orange'];
colors.removeAt(0); // ['green', 'blue', 'yellow', 'orange'] colors.removeAt(2, 2); // ['green', 'blue'] colors.removeAt(4, 2); // Error: Index out of range ```
removeAt
Parameter start
index, start of range
Parameter len
length of passing range {EmberArray} receiver
Modifiers
@public
method removeObject
removeObject: (object: T) => this;
Remove all occurrences of an object in the array.
```javascript let cities = ['Chicago', 'Berlin', 'Lima', 'Chicago'];
cities.removeObject('Chicago'); // ['Berlin', 'Lima'] cities.removeObject('Lima'); // ['Berlin'] cities.removeObject('Tokyo') // ['Berlin'] ```
removeObject
Parameter obj
object to remove {EmberArray} receiver
Modifiers
@public
method removeObjects
removeObjects: (objects: T[]) => this;
Removes each object in the passed array from the receiver.
removeObjects
Parameter objects
the objects to remove {EmberArray} receiver
Modifiers
@public
method replace
replace: (idx: number, amt: number, objects?: readonly T[]) => void;
__Required.__ You must implement this method to apply this mixin.
This is one of the primitives you must implement to support
Array
. You should replace amt objects started at idx with the objects in the passed array.Note that this method is expected to validate the type(s) of objects that it expects.
replace
Parameter idx
Starting index in the array to replace. If idx >= length, then append to the end of the array.
Parameter amt
Number of elements that should be removed from the array, starting at *idx*.
Parameter objects
An optional array of zero or more objects that should be inserted into the array at *idx*
Modifiers
@public
method reverseObjects
reverseObjects: () => this;
Reverse objects in the array. Works just like
reverse()
but it is KVO-compliant.reverseObjects {EmberArray} receiver
Modifiers
@public
method setObjects
setObjects: (object: T[]) => this;
Replace all the receiver's content with content of the argument. If argument is an empty array receiver will be cleared.
```javascript let colors = ['red', 'green', 'blue'];
colors.setObjects(['black', 'white']); // ['black', 'white'] colors.setObjects([]); // [] ```
setObjects
Parameter objects
array whose content will be used for replacing the content of the receiver {EmberArray} receiver with the new content
Modifiers
@public
method shiftObject
shiftObject: () => T | null | undefined;
Shift an object from start of array or nil if none are left. Works just like
shift()
but it is KVO-compliant.```javascript let colors = ['red', 'green', 'blue'];
colors.shiftObject(); // 'red' console.log(colors); // ['green', 'blue'] ```
shiftObject object
Modifiers
@public
method unshiftObject
unshiftObject: (object: T) => T;
Unshift an object to start of array. Works just like
unshift()
but it is KVO-compliant.```javascript let colors = ['red'];
colors.unshiftObject('yellow'); // ['yellow', 'red'] colors.unshiftObject(['black']); // [['black'], 'yellow', 'red'] ```
unshiftObject
Parameter obj
object to unshift object same object passed as a param
Modifiers
@public
method unshiftObjects
unshiftObjects: (objects: T[]) => this;
Adds the named objects to the beginning of the array. Defers notifying observers until all objects have been added.
```javascript let colors = ['red'];
colors.unshiftObjects(['black', 'white']); // ['black', 'white', 'red'] colors.unshiftObjects('yellow'); // Type Error: 'undefined' is not a function ```
unshiftObjects
Parameter objects
the objects to add {EmberArray} receiver
Modifiers
@public
namespace @ember/array/proxy
module '@ember/array/proxy' {}
class ArrayProxy
class ArrayProxy<T> extends EmberObject implements PropertyDidChange {}
property arrangedContent
arrangedContent: EmberArray<T>;
property content
content: T[] | EmberArray<T> | NativeArray<T>;
property length
length: number;
method [PROPERTY_DID_CHANGE]
[PROPERTY_DID_CHANGE]: () => void;
method init
init: (props: object | undefined) => void;
method objectAt
objectAt: (idx: number) => T | undefined;
method replace
replace: (idx: number, amt: number, objects?: T[]) => void;
method willDestroy
willDestroy: () => void;
interface ArrayProxy
interface ArrayProxy<T> extends MutableArray<T> {}
An ArrayProxy wraps any other object that implements
Array
and/orMutableArray,
forwarding all requests. This makes it very useful for a number of binding use cases or other cases where being able to swap out the underlying array is useful.A simple example of usage:
```javascript import { A } from '@ember/array'; import ArrayProxy from '@ember/array/proxy';
let pets = ['dog', 'cat', 'fish']; let ap = ArrayProxy.create({ content: A(pets) });
ap.get('firstObject'); // 'dog' ap.set('content', ['amoeba', 'paramecium']); ap.get('firstObject'); // 'amoeba' ```
This class can also be useful as a layer to transform the contents of an array, as they are accessed. This can be done by overriding
objectAtContent
:```javascript import { A } from '@ember/array'; import ArrayProxy from '@ember/array/proxy';
let pets = ['dog', 'cat', 'fish']; let ap = ArrayProxy.create({ content: A(pets), objectAtContent: function(idx) { return this.get('content').objectAt(idx).toUpperCase(); } });
ap.get('firstObject'); // . 'DOG' ```
When overriding this class, it is important to place the call to
_super
*after* settingcontent
so the internal observers have a chance to fire properly:```javascript import { A } from '@ember/array'; import ArrayProxy from '@ember/array/proxy';
export default ArrayProxy.extend({ init() { this.set('content', A(['dog', 'cat', 'fish'])); this._super(...arguments); } }); ```
ArrayProxy EmberObject MutableArray
Modifiers
@public
property arrangedContent
arrangedContent: EmberArray<T> | null;
The array that the proxy pretends to be. In the default
ArrayProxy
implementation, this andcontent
are the same. Subclasses ofArrayProxy
can override this property to provide things like sorting and filtering.arrangedContent
Modifiers
@public
property content
content: T[] | EmberArray<T> | NativeArray<T> | null;
The content array. Must be an object that implements
Array
and/orMutableArray.
content EmberArray
Modifiers
@public
method create
create: (init: { content: Array<T> }) => ArrayProxy<T>;
method objectAtContent
objectAtContent: (idx: number) => T | undefined;
Should actually retrieve the object at the specified index from the content. You can override this method in subclasses to transform the content item to something new.
This method will only be called if content is non-
null
.objectAtContent
Parameter idx
The index to retrieve. {Object} the value or undefined if none found
Modifiers
@public
method replaceContent
replaceContent: (idx: number, amt: number, objects?: T[]) => void;
Should actually replace the specified objects on the content array. You can override this method in subclasses to transform the content item into something new.
This method will only be called if content is non-
null
.replaceContent
Parameter idx
The starting index
Parameter amt
The number of items to remove from the content.
Parameter objects
Optional array of objects to insert. {void}
Modifiers
@public
namespace @ember/canary-features
module '@ember/canary-features' {}
variable DEFAULT_FEATURES
const DEFAULT_FEATURES: {};
Set
EmberENV.FEATURES
in your application'sconfig/environment.js
file to enable canary features in your application.See the [feature flag guide](https://guides.emberjs.com/release/configuring-ember/feature-flags/) for more details.
@ember/canary-features
Modifiers
@public
variable FEATURES
const FEATURES: { [feature: string]: boolean };
The hash of enabled Canary features. Add to this, any canary features before creating your application.
FEATURES 1.1.0
Modifiers
@public
function isEnabled
isEnabled: (feature: string) => boolean;
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_OPTIONAL_FEATURES
- enable any features that have not been explicitly enabled/disabled.isEnabled
Parameter feature
The feature to check {Boolean} 1.1.0
Modifiers
@public
namespace @ember/component
module '@ember/component' {}
variable Input
const Input: Input;
variable Textarea
const Textarea: Textarea;
function setComponentManager
setComponentManager: <T extends object>( manager: (owner: InternalOwner) => ComponentManager<unknown>, obj: T) => T;
Associate a class with a component manager (an object that is responsible for coordinating the lifecycle events that occurs when invoking, rendering and re-rendering a component).
setComponentManager
Parameter factory
a function to create the owner for an object
Parameter obj
the object to associate with the componetn manager {Object} the same object passed in
Modifiers
@public
class Component
class Component<S = unknown> extends Component_base implements PropertyDidChange {}
property [DIRTY_TAG]
[DIRTY_TAG]: DirtyableTag;
property [IS_DISPATCHING_ATTRS]
[IS_DISPATCHING_ATTRS]: boolean;
property ariaRole
ariaRole?: string;
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: [https://www.w3.org/TR/wai-aria/#roles_categorization](https://www.w3.org/TR/wai-aria/#roles_categorization)
ariaRole String undefined
Modifiers
@public
property attributeBindings
attributeBindings?: string[];
property isComponent
isComponent: boolean;
property isComponentFactory
static isComponentFactory: boolean;
property layout
layout?: any;
Layout can be used to wrap content in a component. layout Function
Modifiers
@public
property layoutName
layoutName?: string;
The name of the layout to lookup if no layout is provided. By default
Component
will lookup a template with this name inEmber.TEMPLATES
(a shared global object). layoutName String undefined
property positionalParams
static positionalParams: string | string[];
Enables components to take a list of parameters as arguments. For example, a component that takes two parameters with the names
name
andage
:```app/components/my-component.js import Component from '@ember/component';
let MyComponent = Component.extend();
MyComponent.reopenClass({ positionalParams: ['name', 'age'] });
export default MyComponent; ```
It can then be invoked like this:
```hbs {{my-component "John" 38}} ```
The parameters can be referred to just like named parameters:
```hbs Name: {{name}}, Age: {{age}}. ```
Using a string instead of an array allows for an arbitrary number of parameters:
```app/components/my-component.js import Component from '@ember/component';
let MyComponent = Component.extend();
MyComponent.reopenClass({ positionalParams: 'names' });
export default MyComponent; ```
It can then be invoked like this:
```hbs {{my-component "John" "Michael" "Scott"}} ``` The parameters can then be referred to by enumerating over the list:
```hbs {{#each names as |name|}}{{name}}{{/each}} ```
positionalParams 1.13.0
Modifiers
@public
method [PROPERTY_DID_CHANGE]
[PROPERTY_DID_CHANGE]: (key: string, value?: unknown) => void;
method getAttr
getAttr: (key: string) => unknown;
method init
init: (properties?: object | undefined) => void;
method on
on: { <Target>( name: string, target: Target, method: string | ((this: Target, ...args: any[]) => void) ): this; (name: string, method: string | ((...args: any[]) => void)): this;};
method readDOMAttr
readDOMAttr: (name: string) => any;
Normally, Ember's component model is "write-only". The component takes a bunch of attributes that it got passed in, and uses them to render its template.
One nice thing about this model is that if you try to set a value to the same thing as last time, Ember (through HTMLBars) will avoid doing any work on the DOM.
This is not just a performance optimization. If an attribute has not changed, it is important not to clobber the element's "hidden state". For example, if you set an input's
value
to the same value as before, it will clobber selection state and cursor position. In other words, setting an attribute is not **always** idempotent.This method provides a way to read an element's attribute and also update the last value Ember knows about at the same time. This makes setting an attribute idempotent.
In particular, what this means is that if you get an
<input>
element'svalue
attribute and then re-render the template with the same value, it will avoid clobbering the cursor and selection position. Since most attribute sets are idempotent in the browser, you typically can get away with reading attributes using jQuery, but the most reliable way to do so is through this method. readDOMAttrParameter name
the name of the attribute String
Modifiers
@public
method toString
static toString: () => string;
interface Component
interface Component<S = unknown> extends CoreView, ChildViewsSupport, ViewStateSupport, ClassNamesSupport, TargetActionSupport, ActionSupport, ViewMixin, ComponentMethods {}
A component is a reusable UI element that consists of a
.hbs
template and an optional JavaScript class that defines its behavior. For example, someone might make abutton
in the template and handle the click behavior in the JavaScript file that shares the same name as the template.Components are broken down into two categories:
- Components _without_ JavaScript, that are based only on a template. These are called Template-only or TO components. - Components _with_ JavaScript, which consist of a template and a backing class.
Ember ships with two types of JavaScript classes for components:
1. Glimmer components, imported from
@glimmer/component
, which are the default component's for Ember Octane (3.15) and more recent editions. 2. Classic components, imported from@ember/component
, which were the default for older editions of Ember (pre 3.15).Below is the documentation for Classic components. If you are looking for the API documentation for Template-only or Glimmer components, it is [available here](/ember/release/modules/@glimmer%2Fcomponent).
## Defining a Classic Component
If you want to customize the component in order to handle events, transform arguments or maintain internal state, you implement a subclass of
Component
.One example is to add computed properties to your component:
```app/components/person-profile.js import Component from '@ember/component';
export default Component.extend({ displayName: computed('person.title', 'person.firstName', 'person.lastName', function() { let { title, firstName, lastName } = this.person;
if (title) { return
${title} ${lastName}
; } else { return${firstName} ${lastName}
; } }) }); ```And then use it in the component's template:
```app/templates/components/person-profile.hbs {{this.displayName}} {{yield}} ```
## Customizing a Classic Component's HTML Element in JavaScript
### HTML Tag
The default HTML tag name used for a component's HTML representation is
div
. This can be customized by setting thetagName
property.Consider the following component class:
```app/components/emphasized-paragraph.js import Component from '@ember/component';
export default Component.extend({ tagName: 'em' }); ```
When invoked, this component would produce output that looks something like this:
```html ```
### HTML
class
AttributeThe HTML
class
attribute of a component's tag can be set by providing aclassNames
property that is set to an array of strings:```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ classNames: ['my-class', 'my-other-class'] }); ```
Invoking this component will produce output that looks like this:
```html ```
class
attribute values can also be set by providing aclassNameBindings
property set to an array of properties names for the component. The return value of these properties will be added as part of the value for the components'sclass
attribute. These properties can be computed properties:```app/components/my-widget.js import Component from '@ember/component'; import { computed } from '@ember/object';
export default Component.extend({ classNames: ['my-class', 'my-other-class'], classNameBindings: ['propertyA', 'propertyB'],
propertyA: 'from-a', propertyB: computed(function() { if (someLogic) { return 'from-b'; } }) }); ```
Invoking this component will produce HTML that looks like:
```html ```
Note that
classNames
andclassNameBindings
is in addition to theclass
attribute passed with the angle bracket invocation syntax. Therefore, if this component was invoked like so:```handlebars ```
The resulting HTML will look similar to this:
```html ```
If the value of a class name binding returns a boolean the property name itself will be used as the class name if the property is true. The class name will not be added if the value is
false
orundefined
.```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ classNameBindings: ['hovered'],
hovered: true }); ```
Invoking this component will produce HTML that looks like:
```html ```
### Custom Class Names for Boolean Values
When using boolean class name bindings you can supply a string value other than the property name for use as the
class
HTML attribute by appending the preferred value after a ":" character when defining the binding:```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ classNameBindings: ['awesome:so-very-cool'],
awesome: true }); ```
Invoking this component will produce HTML that looks like:
```html ```
Boolean value class name bindings whose property names are in a camelCase-style format will be converted to a dasherized format:
```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ classNameBindings: ['isUrgent'],
isUrgent: true }); ```
Invoking this component will produce HTML that looks like:
```html ```
Class name bindings can also refer to object values that are found by traversing a path relative to the component itself:
```app/components/my-widget.js import Component from '@ember/component'; import EmberObject from '@ember/object';
export default Component.extend({ classNameBindings: ['messages.empty'],
messages: EmberObject.create({ empty: true }) }); ```
Invoking this component will produce HTML that looks like:
```html ```
If you want to add a class name for a property which evaluates to true and and a different class name if it evaluates to false, you can pass a binding like this:
```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ classNameBindings: ['isEnabled:enabled:disabled'], isEnabled: true }); ```
Invoking this component will produce HTML that looks like:
```html ```
When isEnabled is
false
, the resulting HTML representation looks like this:```html ```
This syntax offers the convenience to add a class if a property is
false
:```app/components/my-widget.js import Component from '@ember/component';
// Applies no class when isEnabled is true and class 'disabled' when isEnabled is false export default Component.extend({ classNameBindings: ['isEnabled::disabled'], isEnabled: true }); ```
Invoking this component when the
isEnabled
property is true will produce HTML that looks like:```html ```
Invoking it when the
isEnabled
property on the component isfalse
will produce HTML that looks like:```html ```
Updates to the value of a class name binding will result in automatic update of the HTML
class
attribute in the component's rendered HTML representation. If the value becomesfalse
orundefined
the class name will be removed.Both
classNames
andclassNameBindings
are concatenated properties. See [EmberObject](/ember/release/classes/EmberObject) documentation for more information about concatenated properties.### Other HTML Attributes
The HTML attribute section of a component's tag can be set by providing an
attributeBindings
property set to an array of property names on the component. The return value of these properties will be used as the value of the component's HTML associated attribute:```app/components/my-anchor.js import Component from '@ember/component';
export default Component.extend({ tagName: 'a', attributeBindings: ['href'],
href: 'http://google.com' }); ```
Invoking this component will produce HTML that looks like:
```html ```
One property can be mapped on to another by placing a ":" between the source property and the destination property:
```app/components/my-anchor.js import Component from '@ember/component';
export default Component.extend({ tagName: 'a', attributeBindings: ['url:href'],
url: 'http://google.com' }); ```
Invoking this component will produce HTML that looks like:
```html ```
HTML attributes passed with angle bracket invocations will take precedence over those specified in
attributeBindings
. Therefore, if this component was invoked like so:```handlebars <MyAnchor href="http://bing.com" @url="http://google.com" /> ```
The resulting HTML will looks like this:
```html ```
Note that the
href
attribute is ultimately set tohttp://bing.com
, despite it having attribute binidng to theurl
property, which was set tohttp://google.com
.Namespaced attributes (e.g.
xlink:href
) are supported, but have to be mapped, since:
is not a valid character for properties in Javascript:```app/components/my-use.js import Component from '@ember/component';
export default Component.extend({ tagName: 'use', attributeBindings: ['xlinkHref:xlink:href'],
xlinkHref: '#triangle' }); ```
Invoking this component will produce HTML that looks like:
```html <use xlink:href="#triangle"> ```
If the value of a property monitored by
attributeBindings
is a boolean, the attribute will be present or absent depending on the value:```app/components/my-text-input.js import Component from '@ember/component';
export default Component.extend({ tagName: 'input', attributeBindings: ['disabled'],
disabled: false }); ```
Invoking this component will produce HTML that looks like:
```html ```
attributeBindings
can refer to computed properties:```app/components/my-text-input.js import Component from '@ember/component'; import { computed } from '@ember/object';
export default Component.extend({ tagName: 'input', attributeBindings: ['disabled'],
disabled: computed(function() { if (someLogic) { return true; } else { return false; } }) }); ```
To prevent setting an attribute altogether, use
null
orundefined
as the value of the property used inattributeBindings
:```app/components/my-text-input.js import Component from '@ember/component';
export default Component.extend({ tagName: 'form', attributeBindings: ['novalidate'], novalidate: null }); ```
Updates to the property of an attribute binding will result in automatic update of the HTML attribute in the component's HTML output.
attributeBindings
is a concatenated property. See [EmberObject](/ember/release/classes/EmberObject) documentation for more information about concatenated properties.## Layouts
The
layout
property can be used to dynamically specify a template associated with a component class, instead of relying on Ember to link together a component class and a template based on file names.In general, applications should not use this feature, but it's commonly used in addons for historical reasons.
The
layout
property should be set to the default export of a template module, which is the name of a template file without the.hbs
extension.```app/templates/components/person-profile.hbs Person's Title {{yield}} ```
```app/components/person-profile.js import Component from '@ember/component'; import layout from '../templates/components/person-profile';
export default Component.extend({ layout }); ```
If you invoke the component:
```handlebars Chief Basket Weaver Fisherman Industries ```
or
```handlebars {{#person-profile}} Chief Basket Weaver Fisherman Industries {{/person-profile}} ```
It will result in the following HTML output:
```html Person's Title Chief Basket Weaver Fisherman Industries ```
## Handling Browser Events
There are two ways to handle user-initiated events:
### Using the
on
modifier to capture browser eventsIn a component's template, you can attach an event handler to any element with the
on
modifier:```handlebars <button {{on 'click' this.doSomething}} /> ```
This will call the function on your component:
```js import Component from '@ember/component';
export default class ExampleComponent extends Component { doSomething = (event) => { //
event
is the native click Event console.log('clicked on the button'); }; }); ```See the [Guide on Component event handlers](https://guides.emberjs.com/release/components/component-state-and-actions/#toc_html-modifiers-and-actions) and the [API docs for
on
](../Ember.Templates.helpers/methods/on?anchor=on) for more details.### Event Handler Methods
Components can also respond to user-initiated events by implementing a method that matches the event name. This approach is appropriate when the same event should be handled by all instances of the same component.
An event object will be passed as the argument to the event handler method.
```app/components/my-widget.js import Component from '@ember/component';
export default Component.extend({ click(event) { //
event.target
is either the component's element or one of its children let tag = event.target.tagName.toLowerCase(); console.log('clicked on a<${tag}>
HTML element!'); } }); ```In this example, whenever the user clicked anywhere inside the component, it will log a message to the console.
It is possible to handle event types other than
click
by implementing the following event handler methods. In addition, custom events can be registered by usingApplication.customEvents
.Touch events:
touchStart
touchMove
touchEnd
touchCancel
Keyboard events:
keyDown
keyUp
keyPress
Mouse events:
mouseDown
mouseUp
contextMenu
click
doubleClick
focusIn
focusOut
Form events:
submit
change
focusIn
focusOut
input
Drag and drop events:
dragStart
drag
dragEnter
dragLeave
dragOver
dragEnd
drop
Component Ember.CoreView Ember.TargetActionSupport Ember.ClassNamesSupport Ember.ActionSupport Ember.ViewMixin Ember.ViewStateSupport
Modifiers
@public
interface Input
interface Input extends Opaque<'component:input'>, OpaqueInternalComponentConstructor {}
interface Textarea
interface Textarea extends Opaque<'component:textarea'>, OpaqueInternalComponentConstructor {}
namespace @ember/component/helper
module '@ember/component/helper' {}
function helper
helper: { <P extends DefaultPositional, N extends object, R = unknown>( helperFn: (positional: P, named: N) => R ): FunctionBasedHelper<{ Args: { Positional: P; Named: N }; Return: R }>; <S>( helperFn: ( positional: GetOr<GetOr<S, 'Args', {}>, 'Positional', DefaultPositional>, named: GetOr<GetOr<S, 'Args', {}>, 'Named', object> ) => GetOr<S, 'Return', unknown> ): FunctionBasedHelper<S>;};
In many cases it is not necessary to use the full
Helper
class. Thehelper
method create pure-function helpers without instances. For example:```app/helpers/format-currency.js import { helper } from '@ember/component/helper';
export default helper(function([cents], {currency}) { return
${currency}${cents * 0.01}
; }); ```Parameter helper
The helper function helper @ember/component/helper
1.13.0
Modifiers
@public
class FunctionBasedHelperInstance
abstract class FunctionBasedHelperInstance<S> extends Helper<S> {}
class Helper
class Helper<S = unknown> extends FrameworkObject {}
property [IS_CLASSIC_HELPER]
static [IS_CLASSIC_HELPER]: boolean;
property [RECOMPUTE_TAG]
[RECOMPUTE_TAG]: DirtyableTag;
property helper
static helper: { <P extends DefaultPositional, N extends object, R = unknown>( helperFn: (positional: P, named: N) => R ): FunctionBasedHelper<{ Args: { Positional: P; Named: N }; Return: R }>; <S>( helperFn: ( positional: GetOr< GetOr<S, 'Args', {}>, 'Positional', DefaultPositional >, named: GetOr<GetOr<S, 'Args', {}>, 'Named', object> ) => GetOr<S, 'Return', unknown> ): FunctionBasedHelper<S>;};
Deprecated
property isHelperFactory
static isHelperFactory: boolean;
method init
init: (properties: object | undefined) => void;
method recompute
recompute: () => void;
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:```app/helpers/current-user-email.js import Helper from '@ember/component/helper' import { service } from '@ember/service' import { observer } from '@ember/object'
export default Helper.extend({ session: service(),
onNewUser: observer('session.currentUser', function() { this.recompute(); }),
compute() { return this.get('session.currentUser.email'); } }); ```
recompute
1.13.0
Modifiers
@public
interface Helper
interface Helper<S = unknown> {}
Ember Helpers are functions that can compute values, and are used in templates. For example, this code calls a helper named
format-currency
:```app/templates/application.hbs <Cost @cents={{230}} /> ```
```app/components/cost.hbs {{format-currency currency="$"}} ```
Additionally a helper can be called as a nested helper. In this example, we show the formatted currency value if the
showMoney
named argument is truthy.```handlebars {{if (format-currency currency="$")}} ```
Helpers defined using a class must provide a
compute
function. For example:```app/helpers/format-currency.js import Helper from '@ember/component/helper';
export default class extends Helper { compute([cents], { 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 and will accept injected dependencies.
Additionally, class helpers can call
recompute
to force a new computation.Helper CoreObject
1.13.0
Modifiers
@public
method compute
compute: (positional: Positional<S>, named: Named<S>) => Return<S>;
Override this function when writing a class-based helper.
compute
Parameter positional
The positional arguments to the helper
Parameter named
The named arguments to the helper
1.13.0
Modifiers
@public
type FunctionBasedHelper
type FunctionBasedHelper<S> = abstract new () => FunctionBasedHelperInstance<S>;
The type of a function-based helper.
This is *not* user-constructible: it is exported only so that the type returned by the
helper
function can be named (and indeed can be exported likeexport default helper(...)
safely).
namespace @ember/component/template-only
module '@ember/component/template-only' {}
function templateOnly
templateOnly: <S>( moduleName?: string, name?: string) => TemplateOnlyComponent<S>;
interface TemplateOnlyComponent
interface TemplateOnlyComponent<S = unknown> extends Opaque<S> {}
Template-only components have no backing class instance, so
this
in their templates is null. This means that you can only reference passed in arguments (e.g.{{@arg}}
).
type TOC
type TOC<S> = TemplateOnlyComponent<S>;
A convenience alias for TemplateOnlyComponent
namespace @ember/controller
module '@ember/controller' {}
variable ControllerMixin
const ControllerMixin: Mixin;
function inject
inject: { (name: string): PropertyDecorator; (args_0: object, args_1: string): void; ( target: object, propertyName: string, descriptor?: PropertyDescriptor & { initializer?: any } ): PropertyDescriptor & { initializer?: any }; (): PropertyDecorator;};
Creates a property that lazily looks up another controller in the container. Can only be used when defining another controller.
Example:
```app/controllers/post.js import Controller, { inject as controller } from '@ember/controller';
export default class PostController extends Controller { posts; } ```
Classic Class Example:
```app/controllers/post.js import Controller, { inject as controller } from '@ember/controller';
export default Controller.extend({ posts: controller() }); ```
This example will create a
posts
property on thepost
controller that looks up theposts
controller in the container, making it easy to reference other controllers.inject @ember/controller 1.10.0
Parameter name
(optional) name of the controller to inject, defaults to the property's name {ComputedDecorator} injection decorator instance
Modifiers
@public
class Controller
class Controller<_T = unknown> extends Controller_base {}
interface Controller
interface Controller<_T = unknown> extends FrameworkObject, ControllerMixin<_T> {}
Controller EmberObject Ember.ControllerMixin
Modifiers
@public
interface ControllerMixin
interface ControllerMixin<T> extends ActionHandler {}
ControllerMixin Ember Ember.ActionHandler
property isController
isController: true;
property model
model: T;
The controller's current model. When retrieving or modifying a controller's model, this property should be used instead of the
content
property.model
Modifiers
@public
property queryParams
queryParams: Readonly<Array<ControllerQueryParam>>;
Defines which query parameters the controller accepts. If you give the names
['category','page']
it will bind the values of these query parameters to the variablesthis.category
andthis.page
.By default, query parameters are parsed as strings. This may cause unexpected behavior if a query parameter is used with
toggleProperty
, because the initial value set forparam=false
will be the string"false"
, which is truthy.To avoid this, you may specify that the query parameter should be parsed as a boolean by using the following verbose form with a
type
property: ```javascript queryParams: [{ category: { type: 'boolean' } }] ``` Available values for thetype
parameter are'boolean'
,'number'
,'array'
, and'string'
. If query param type is not specified, it will default to'string'
.Ember.ControllerMixin queryParams
Modifiers
@public
property target
target: unknown | null;
The object to which actions from the view should be sent.
For example, when a Handlebars template uses the
{{action}}
helper, it will attempt to send the action to the view's controller'starget
.By default, the value of the target property is set to the router, and is injected when a controller is instantiated. This injection is applied as part of the application's initialization process. In most cases the
target
property will automatically be set to the logical consumer of actions for the controller.target null
Modifiers
@public
method replaceRoute
replaceRoute: (...args: RouteArgs) => Transition;
Transition into another route while replacing the current URL, if possible. This will replace the current history entry instead of adding a new one. Beside that, it is identical to
transitionToRoute
in all other respects.```javascript aController.replaceRoute('blogPosts'); aController.replaceRoute('blogPosts.recentEntries'); ```
Optionally supply a model for the route in question. The model will be serialized into the URL using the
serialize
hook of the route:```javascript aController.replaceRoute('blogPost', aPost); ```
If a literal is passed (such as a number or a string), it will be treated as an identifier instead. In this case, the
model
hook of the route will be triggered:```javascript aController.replaceRoute('blogPost', 1); ```
Multiple models will be applied last to first recursively up the route tree.
```app/router.js Router.map(function() { this.route('blogPost', { path: ':blogPostId' }, function() { this.route('blogComment', { path: ':blogCommentId', resetNamespace: true }); }); }); ```
``` aController.replaceRoute('blogComment', aPost, aComment); aController.replaceRoute('blogComment', 1, 13); ```
It is also possible to pass a URL (a string that starts with a
/
).```javascript aController.replaceRoute('/'); aController.replaceRoute('/blog/post/1/comment/13'); ```
Ember.ControllerMixin replaceRoute
Parameter name
the name of the route or a URL
Parameter models
the model(s) or identifier(s) to be used while transitioning to the route.
Parameter options
optional hash with a queryParams property containing a mapping of query parameters {Transition} the transition object associated with this attempted transition
Modifiers
@public
Deprecated
Use replaceWith from the Router service instead.
method transitionToRoute
transitionToRoute: (...args: RouteArgs) => Transition;
Transition the application into another route. The route may be either a single route or route path:
```javascript aController.transitionToRoute('blogPosts'); aController.transitionToRoute('blogPosts.recentEntries'); ```
Optionally supply a model for the route in question. The model will be serialized into the URL using the
serialize
hook of the route:```javascript aController.transitionToRoute('blogPost', aPost); ```
If a literal is passed (such as a number or a string), it will be treated as an identifier instead. In this case, the
model
hook of the route will be triggered:```javascript aController.transitionToRoute('blogPost', 1); ```
Multiple models will be applied last to first recursively up the route tree.
```app/router.js Router.map(function() { this.route('blogPost', { path: ':blogPostId' }, function() { this.route('blogComment', { path: ':blogCommentId', resetNamespace: true }); }); }); ```
```javascript aController.transitionToRoute('blogComment', aPost, aComment); aController.transitionToRoute('blogComment', 1, 13); ```
It is also possible to pass a URL (a string that starts with a
/
).```javascript aController.transitionToRoute('/'); aController.transitionToRoute('/blog/post/1/comment/13'); aController.transitionToRoute('/blog/posts?sort=title'); ```
An options hash with a
queryParams
property may be provided as the final argument to add query parameters to the destination URL.```javascript aController.transitionToRoute('blogPost', 1, { queryParams: { showComments: 'true' } });
// if you just want to transition the query parameters without changing the route aController.transitionToRoute({ queryParams: { sort: 'date' } }); ```
See also [replaceRoute](/ember/release/classes/Ember.ControllerMixin/methods/replaceRoute?anchor=replaceRoute).
Ember.ControllerMixin transitionToRoute
Parameter name
the name of the route or a URL
Parameter models
the model(s) or identifier(s) to be used while transitioning to the route.
Parameter options
optional hash with a queryParams property containing a mapping of query parameters {Transition} the transition object associated with this attempted transition
Modifiers
@public
Deprecated
Use transitionTo from the Router service instead.
interface Registry
interface Registry extends Record<string, Controller | undefined> {}
A type registry for Ember
Controller
s. Meant to be declaration-merged so string lookups resolve to the correct type.Blueprints should include such a declaration merge for TypeScript:
```ts import Controller from '@ember/controller';
export default class ExampleController extends Controller { // ... }
declare module '@ember/controller' { export interface Registry { example: ExampleController; } } ```
Then
@inject
can check that the service is registered correctly, and APIs likeowner.lookup('controller:example')
can returnExampleController
.
type ControllerQueryParam
type ControllerQueryParam = | string | Record< string, { type: ControllerQueryParamType; } > | Record<string, string>;
type ControllerQueryParamType
type ControllerQueryParamType = 'boolean' | 'number' | 'array' | 'string';
namespace @ember/debug
module '@ember/debug' {}
variable assert
let assert: AssertFunc;
variable debug
let debug: DebugFunc;
variable debugFreeze
let debugFreeze: DebugFreezeFunc;
variable debugSeal
let debugSeal: DebugSealFunc;
variable deprecateFunc
let deprecateFunc: DeprecateFuncFunc;
variable getDebugFunction
let getDebugFunction: GetDebugFunction;
variable info
let info: InfoFunc;
variable registerWarnHandler
let registerWarnHandler: RegisterHandlerFunc;
variable runInDebug
let runInDebug: RunInDebugFunc;
variable setDebugFunction
let setDebugFunction: SetDebugFunction;
variable warn
let warn: WarnFunc;
function captureRenderTree
captureRenderTree: (app: Owner) => CapturedRenderNode[];
Ember Inspector calls this function to capture the current render tree.
In production mode, this requires turning on
ENV._DEBUG_RENDER_TREE
before loading Ember.captureRenderTree @ember/debug
Parameter app
An
ApplicationInstance
. 3.14.0
function deprecate
deprecate: ( message: string, test?: boolean, options?: DeprecationOptions) => ReturnType<DeprecateFunc>;
function inspect
inspect: (this: any, obj: any | null | undefined) => string;
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
inspect
Parameter obj
The object you want to inspect. {String} A description of the object 1.4.0
function isTesting
isTesting: () => boolean;
function registerDeprecationHandler
registerDeprecationHandler: ( handler: HandlerCallback<DeprecationOptions>) => void;
Allows for runtime registration of handler functions that override the default deprecation behavior. Deprecations are invoked by calls to [@ember/debug/deprecate](/ember/release/classes/@ember%2Fdebug/methods/deprecate?anchor=deprecate). The following example demonstrates its usage by registering a handler that throws an error if the message contains the word "should", otherwise defers to the default handler.
```javascript import { registerDeprecationHandler } from '@ember/debug';
registerDeprecationHandler((message, options, next) => { if (message.indexOf('should') !== -1) { throw new Error(
Deprecation message with should: ${message}
); } else { // defer to whatever handler was registered before this one next(message, options); } }); ```The handler function takes the following arguments:
message - The message received from the deprecation call. options - An object passed in with the deprecation call containing additional information including: id - An id of the deprecation in the form of package-name.specific-deprecation. until - The Ember version number the feature and deprecation will be removed in. next - A function that calls into the previously registered handler.
registerDeprecationHandler @ember/debug
Parameter handler
A function to handle deprecation calls. 2.1.0
Modifiers
@public
function setTesting
setTesting: (value: boolean) => void;
interface DeprecationOptions
interface DeprecationOptions {}
type DebugFreezeFunc
type DebugFreezeFunc = (obj: object) => void;
type DebugFunc
type DebugFunc = (message: string) => void;
type DebugFunctionType
type DebugFunctionType = | 'assert' | 'info' | 'warn' | 'debug' | 'deprecate' | 'debugSeal' | 'debugFreeze' | 'runInDebug' | 'deprecateFunc';
type DebugSealFunc
type DebugSealFunc = (obj: object) => void;
type DeprecateFuncFunc
type DeprecateFuncFunc = ( message: string, options: DeprecationOptions, func: Function) => Function;
type GetDebugFunction
type GetDebugFunction = { (type: 'assert'): typeof assert; (type: 'info'): InfoFunc; (type: 'warn'): WarnFunc; (type: 'debug'): DebugFunc; (type: 'debugSeal'): DebugSealFunc; (type: 'debugFreeze'): DebugFreezeFunc; (type: 'deprecateFunc'): DeprecateFuncFunc; (type: 'deprecate'): DeprecateFunc; (type: 'runInDebug'): RunInDebugFunc;};
type InfoFunc
type InfoFunc = (message: string, options?: object) => void;
type RunInDebugFunc
type RunInDebugFunc = (func: () => void) => void;
type SetDebugFunction
type SetDebugFunction = { (type: 'assert', func: typeof assert): typeof assert; (type: 'info', func: InfoFunc): InfoFunc; (type: 'warn', func: WarnFunc): WarnFunc; (type: 'debug', func: DebugFunc): DebugFunc; (type: 'debugSeal', func: DebugSealFunc): DebugSealFunc; (type: 'debugFreeze', func: DebugFreezeFunc): DebugFreezeFunc; (type: 'deprecateFunc', func: DeprecateFuncFunc): DeprecateFuncFunc; (type: 'deprecate', func: DeprecateFunc): DeprecateFunc; (type: 'runInDebug', func: RunInDebugFunc): RunInDebugFunc;};
namespace @ember/debug/container-debug-adapter
module '@ember/debug/container-debug-adapter' {}
class ContainerDebugAdapter
class ContainerDebugAdapter extends EmberObject {}
The
ContainerDebugAdapter
helps the container and resolver interface with tools that debug Ember such as the [Ember Inspector](https://github.com/emberjs/ember-inspector) 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(application) { application.register('container-debug-adapter:main', require('app/container-debug-adapter')); } }); ```
ContainerDebugAdapter EmberObject 1.5.0
Modifiers
@public
constructor
constructor(owner: Owner);
property resolver
resolver: Resolver;
The resolver instance of the application being debugged. This property will be injected on creation.
resolver
Modifiers
@public
method canCatalogEntriesByType
canCatalogEntriesByType: (type: string) => boolean;
Returns true if it is possible to catalog a list of available classes in the resolver for a given type.
canCatalogEntriesByType
Parameter type
The type. e.g. "model", "controller", "route". {boolean} whether a list is available for this type.
Modifiers
@public
method catalogEntriesByType
catalogEntriesByType: (type: string) => string[];
Returns the available classes a given type.
catalogEntriesByType
Parameter type
The type. e.g. "model", "controller", "route". {Array} An array of strings.
Modifiers
@public
namespace @ember/debug/data-adapter
module '@ember/debug/data-adapter' {}
class DataAdapter
class DataAdapter<T> extends EmberObject {}
The
DataAdapter
helps a data persistence library interface with tools that debug Ember such as the [Ember Inspector](https://github.com/emberjs/ember-inspector) 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
The adapter will need to be registered in the application's container as
dataAdapter:main
.Example:
```javascript Application.initializer({ name: "data-adapter",
initialize: function(application) { application.register('data-adapter:main', DS.DataAdapter); } }); ```
DataAdapter EmberObject
Modifiers
@public
constructor
constructor(owner: Owner);
property acceptsModelName
acceptsModelName: boolean;
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.
acceptsModelName
Modifiers
@public
property attributeLimit
attributeLimit: number;
The number of attributes to send as columns. (Enough to make the record identifiable).
attributeLimit 3 1.3.0
property containerDebugAdapter
containerDebugAdapter: ContainerDebugAdapter;
property flushWatchers
flushWatchers: () => void;
property recordsWatchers
recordsWatchers: Map<unknown, { release: () => void; revalidate: () => void }>;
property releaseMethods
releaseMethods: NativeArray<() => void>;
property typeWatchers
typeWatchers: Map<unknown, { release: () => void; revalidate: () => void }>;
method columnsForType
columnsForType: (_klass: unknown) => Column[];
Get the columns for a given model type.
columnsForType {Array} An array of columns of the following format: name: {String} The name of the column. desc: {String} Humanized description (what would show in a table column name).
Modifiers
@public
method detect
detect: (_klass: unknown) => boolean;
Detect whether a class is a model.
Test that against the model class of your persistence library.
detect boolean Whether the class is a model class or not.
Modifiers
@public
method getFilters
getFilters: () => Array<{ name: string; desc: string }>;
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.getFilters {Array} List of objects defining filters. The object should have a
name
anddesc
property.Modifiers
@public
method getModelTypes
getModelTypes: () => Array<{ klass: unknown; name: string }>;
Fetches all models defined in the application.
getModelTypes {Array} Array of model types.
method getRecordColor
getRecordColor: (_record: T) => RecordColor | null;
Each record can have a color that represents its state.
getRecordColor
Parameter record
The record instance {String} The records color. Possible options: black, red, blue, green.
Modifiers
@public
method getRecordColumnValues
getRecordColumnValues: (_record: T) => {};
Gets the values for each column.
getRecordColumnValues {Object} Keys should match column names defined by the model type.
Modifiers
@public
method getRecordFilterValues
getRecordFilterValues: (_record: T) => object;
Returns the values of filters defined by
getFilters
.getRecordFilterValues
Parameter record
The record instance. {Object} The filter values.
Modifiers
@public
method getRecordKeywords
getRecordKeywords: (_record: T) => NativeArray<unknown>;
Returns keywords to match when searching records.
getRecordKeywords {Array} Relevant keywords for search.
Modifiers
@public
method getRecords
getRecords: (_klass: unknown, _name: string) => NativeArray<T>;
Fetches all loaded records for a given type.
getRecords {Array} An array of records. This array will be observed for changes, so it should update when new records are added/removed.
Modifiers
@public
method observeModelType
observeModelType: ( modelName: string, typesUpdated: (types: WrappedType[]) => void) => () => void;
Adds observers to a model type class.
observeModelType
Parameter modelName
The model type name.
Parameter typesUpdated
Called when a type is modified. {Function} The function to call to remove observers.
method updateFlushWatchers
updateFlushWatchers: () => void;
method watchModelTypes
watchModelTypes: ( typesAdded: (types: WrappedType[]) => void, typesUpdated: (types: WrappedType[]) => void) => () => void;
Fetch the model types and observe them for changes.
watchModelTypes
Parameter typesAdded
Callback to call to add types. Takes an array of objects containing wrapped types (returned from
wrapModelType
).Parameter typesUpdated
Callback to call when a type has changed. Takes an array of objects containing wrapped types.
{Function} Method to call to remove all observers
Modifiers
@public
method watchRecords
watchRecords: ( modelName: string, recordsAdded: RecordCallback<T>, recordsUpdated: RecordCallback<T>, recordsRemoved: RecordCallback<T>) => () => void;
Fetch the records of a given type and observe them for changes.
watchRecords
Parameter modelName
The model name.
Parameter recordsAdded
Callback to call to add records. Takes an array of objects containing wrapped records. The object should have the following properties: columnValues: {Object} The key and value of a table cell. object: {Object} The actual record object.
Parameter recordsUpdated
Callback to call when a record has changed. Takes an array of objects containing wrapped records.
Parameter recordsRemoved
Callback to call when a record has removed. Takes an array of objects containing wrapped records.
{Function} Method to call to remove all observers.
Modifiers
@public
method willDestroy
willDestroy: () => void;
Clear all observers before destruction willDestroy
method wrapModelType
wrapModelType: <N extends string>(klass: unknown, name: N) => WrappedType<N>;
Wraps a given model type and observes changes to it.
wrapModelType
Parameter klass
A model class.
Parameter modelName
Name of the class. {Object} The wrapped type has the following format: name: {String} The name of the type. count: {Integer} The number of records available. columns: {Columns} An array of columns to describe the record. object: {Class} The actual Model type class.
method wrapRecord
wrapRecord: (record: T) => WrappedRecord<T>;
Wraps a record and observers changes to it.
wrapRecord
Parameter record
The record instance. {Object} The wrapped record. Format: columnValues: {Array} searchKeywords: {Array}
namespace @ember/debug/lib/assert
module '@ember/debug/lib/assert' {}
variable assert
let assert: AssertFunc;
function setAssert
setAssert: (implementation: typeof assert) => typeof assert;
interface AssertFunc
interface AssertFunc {}
call signature
(desc: string, condition: unknown): asserts condition;
call signature
(desc: string): never;
namespace @ember/debug/lib/capture-render-tree
module '@ember/debug/lib/capture-render-tree' {}
function captureRenderTree
captureRenderTree: (app: Owner) => CapturedRenderNode[];
Ember Inspector calls this function to capture the current render tree.
In production mode, this requires turning on
ENV._DEBUG_RENDER_TREE
before loading Ember.captureRenderTree @ember/debug
Parameter app
An
ApplicationInstance
. 3.14.0
namespace @ember/debug/lib/deprecate
module '@ember/debug/lib/deprecate' {}
variable deprecate
let deprecate: DeprecateFunc;
variable missingOptionDeprecation
let missingOptionDeprecation: MissingOptionDeprecateFunc;
variable missingOptionsDeprecation
let missingOptionsDeprecation: string;
variable missingOptionsIdDeprecation
let missingOptionsIdDeprecation: string;
function registerHandler
registerHandler: (handler: HandlerCallback<DeprecationOptions>) => void;
Allows for runtime registration of handler functions that override the default deprecation behavior. Deprecations are invoked by calls to [@ember/debug/deprecate](/ember/release/classes/@ember%2Fdebug/methods/deprecate?anchor=deprecate). The following example demonstrates its usage by registering a handler that throws an error if the message contains the word "should", otherwise defers to the default handler.
```javascript import { registerDeprecationHandler } from '@ember/debug';
registerDeprecationHandler((message, options, next) => { if (message.indexOf('should') !== -1) { throw new Error(
Deprecation message with should: ${message}
); } else { // defer to whatever handler was registered before this one next(message, options); } }); ```The handler function takes the following arguments:
message - The message received from the deprecation call. options - An object passed in with the deprecation call containing additional information including: id - An id of the deprecation in the form of package-name.specific-deprecation. until - The Ember version number the feature and deprecation will be removed in. next - A function that calls into the previously registered handler.
registerDeprecationHandler @ember/debug
Parameter handler
A function to handle deprecation calls. 2.1.0
Modifiers
@public
interface DeprecationOptions
interface DeprecationOptions {}
type DeprecateFunc
type DeprecateFunc = ( message: string, test?: boolean, options?: DeprecationOptions) => void;
type MissingOptionDeprecateFunc
type MissingOptionDeprecateFunc = (id: string, missingOption: string) => string;
namespace @ember/debug/lib/handlers
module '@ember/debug/lib/handlers' {}
variable HANDLERS
let HANDLERS: Handlers;
variable invoke
let invoke: InvokeFunc;
function registerHandler
registerHandler: <O extends object>( _type: string, _callback: HandlerCallback<O>) => void;
interface Handlers
interface Handlers {}
index signature
[key: string]: Handler<Options>;
type Handler
type Handler<O extends Options> = (message: string, options?: O) => void;
type HandlerCallback
type HandlerCallback<O extends Options> = ( message: string, options: O | undefined, nextHandler: Handler<O>) => void;
type InvokeFunc
type InvokeFunc = ( type: string, message: string, test?: boolean, options?: Options) => void;
type Options
type Options = object;
type RegisterHandlerFunc
type RegisterHandlerFunc<O extends Options> = ( type: string, callback: HandlerCallback<O>) => void;
namespace @ember/debug/lib/inspect
module '@ember/debug/lib/inspect' {}
function inspect
inspect: (this: any, obj: any | null | undefined) => string;
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
inspect
Parameter obj
The object you want to inspect. {String} A description of the object 1.4.0
namespace @ember/debug/lib/testing
module '@ember/debug/lib/testing' {}
function isTesting
isTesting: () => boolean;
function setTesting
setTesting: (value: boolean) => void;
namespace @ember/debug/lib/warn
module '@ember/debug/lib/warn' {}
variable missingOptionsDeprecation
let missingOptionsDeprecation: string;
variable missingOptionsIdDeprecation
let missingOptionsIdDeprecation: string;
variable registerHandler
let registerHandler: RegisterHandlerFunc;
variable warn
let warn: WarnFunc;
interface WarnFunc
interface WarnFunc {}
call signature
(message: string): void;
call signature
(message: string, test: boolean): void;
call signature
(message: string, options: WarnOptions): void;
call signature
(message: string, test: boolean, options: WarnOptions): void;
interface WarnOptions
interface WarnOptions {}
property id
id: string;
type RegisterHandlerFunc
type RegisterHandlerFunc = (handler: HandlerCallback<WarnOptions>) => void;
namespace @ember/deprecated-features
module '@ember/deprecated-features' {}
variable ASSIGN
const ASSIGN: boolean;
Introduced in 4.0.0-beta.1
namespace @ember/destroyable
module '@ember/destroyable' {}
function registerDestructor
registerDestructor: <T extends object>( destroyable: T, destructor: (destroyable: T) => void) => (destroyable: T) => void;
Receives a destroyable object and a destructor function, and associates the function with it. When the destroyable is destroyed with destroy, or when its parent is destroyed, the destructor function will be called.
```js import Component from '@glimmer/component'; import { registerDestructor } from '@ember/destroyable';
class Modal extends Component { resize;
constructor(...args) { super(...args);
this.resize.register(this, this.layout);
registerDestructor(this, () => this.resize.unregister(this)); } } ```
Multiple destructors can be associated with a given destroyable, and they can be associated over time, allowing libraries to dynamically add destructors as needed.
registerDestructor
also returns the associated destructor function, for convenience.The destructor function is passed a single argument, which is the destroyable itself. This allows the function to be reused multiple times for many destroyables, rather than creating a closure function per destroyable.
```js import Component from '@glimmer/component'; import { registerDestructor } from '@ember/destroyable';
function unregisterResize(instance) { instance.resize.unregister(instance); }
class Modal extends Component { resize;
constructor(...args) { super(...args);
this.resize.register(this, this.layout);
registerDestructor(this, unregisterResize); } } ```
registerDestructor @ember/destroyable
Parameter destroyable
the destroyable to register the destructor function with
Parameter destructor
the destructor to run when the destroyable object is destroyed
Modifiers
@public
function unregisterDestructor
unregisterDestructor: <T extends object>( destroyable: T, destructor: (destroyable: T) => void) => void;
Receives a destroyable and a destructor function, and de-associates the destructor from the destroyable.
```js import Component from '@glimmer/component'; import { registerDestructor, unregisterDestructor } from '@ember/destroyable';
class Modal extends Component { modals;
constructor(...args) { super(...args);
this.modals.add(this);
this.modalDestructor = registerDestructor(this, () => this.modals.remove(this)); }
pinModal() { unregisterDestructor(this, this.modalDestructor); } } ```
unregisterDestructor @ember/destroyable
Parameter destroyable
the destroyable to unregister the destructor function from
Parameter destructor
the destructor to remove from the destroyable
Modifiers
@public
namespace @ember/engine
module '@ember/engine' {}
function getEngineParent
getEngineParent: (engine: EngineInstance) => EngineInstance | undefined;
getEngineParent
retrieves an engine instance's parent instance.getEngineParent
Parameter engine
An engine instance. {EngineInstance} The parent engine instance. @ember/engine
function setEngineParent
setEngineParent: (engine: EngineInstance, parent: EngineInstance) => void;
setEngineParent
sets an engine instance's parent instance.setEngineParent
Parameter engine
An engine instance.
Parameter parent
The parent engine instance.
class Engine
class Engine extends Engine_base {}
property initializer
static initializer: ( this: typeof Engine, initializer: Initializer<Engine>) => void;
The goal of initializers should be to register dependencies and injections. This phase runs once. Because these initializers may load code, they are allowed to defer application readiness and advance it. If you need to access the container or store you should use an InstanceInitializer that will be run after all initializers and therefore after all code is loaded and the app is ready.
Initializer receives an object which has the following attributes:
name
,before
,after
,initialize
. The only required attribute isinitialize
, 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.```app/initializer/named-initializer.js import { debug } from '@ember/debug';
export function initialize() { debug('Running namedInitializer!'); }
export default { name: 'named-initializer', initialize }; ```
before
andafter
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 thename
of other initializers.An example of ordering initializers, we create an initializer named
first
:```app/initializer/first.js import { debug } from '@ember/debug';
export function initialize() { debug('First initializer!'); }
export default { name: 'first', initialize }; ```
```bash // DEBUG: First initializer! ```
We add another initializer named
second
, specifying that it should run after the initializer namedfirst
:```app/initializer/second.js import { debug } from '@ember/debug';
export function initialize() { debug('Second initializer!'); }
export default { name: 'second', after: 'first', initialize }; ```
``` // DEBUG: First initializer! // DEBUG: Second initializer! ```
Afterwards we add a further initializer named
pre
, this time specifying that it should run before the initializer namedfirst
:```app/initializer/pre.js import { debug } from '@ember/debug';
export function initialize() { debug('Pre initializer!'); }
export default { name: 'pre', before: 'first', initialize }; ```
```bash // DEBUG: Pre initializer! // DEBUG: First initializer! // DEBUG: Second initializer! ```
Finally we add an initializer named
post
, specifying it should run after both thefirst
and thesecond
initializers:```app/initializer/post.js import { debug } from '@ember/debug';
export function initialize() { debug('Post initializer!'); }
export default { name: 'post', after: ['first', 'second'], initialize }; ```
```bash // DEBUG: Pre initializer! // DEBUG: First initializer! // DEBUG: Second initializer! // DEBUG: Post initializer! ```
initialize
is a callback function that receives one argument,application
, on which you can operate.Example of using
application
to register an adapter:```app/initializer/api-adapter.js import ApiAdapter from '../utils/api-adapter';
export function initialize(application) { application.register('api-adapter:main', ApiAdapter); }
export default { name: 'post', after: ['first', 'second'], initialize }; ```
initializer
Parameter initializer
Modifiers
@public
property initializers
static initializers: Record<string, Initializer<Engine>>;
property instanceInitializer
static instanceInitializer: ( this: typeof Engine, initializer: Initializer<EngineInstance>) => void;
Instance initializers run after all initializers have run. Because instance initializers run after the app is fully set up. We have access to the store, container, and other items. However, these initializers run after code has loaded and are not allowed to defer readiness.
Instance initializer receives an object which has the following attributes:
name
,before
,after
,initialize
. The only required attribute isinitialize
, all others are optional.name
allows you to specify under which name the instanceInitializer is registered. This must be a unique name, as trying to register two instanceInitializer with the same name will result in an error.```app/initializer/named-instance-initializer.js import { debug } from '@ember/debug';
export function initialize() { debug('Running named-instance-initializer!'); }
export default { name: 'named-instance-initializer', initialize }; ```
before
andafter
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 thename
of other initializers.See Application.initializer for discussion on the usage of before and after.
Example instanceInitializer to preload data into the store.
```app/initializer/preload-data.js
export function initialize(application) { var userConfig, userConfigEncoded, store; // We have a HTML escaped JSON representation of the user's basic // configuration generated server side and stored in the DOM of the main // index.html file. This allows the app to have access to a set of data // without making any additional remote calls. Good for basic data that is // needed for immediate rendering of the page. Keep in mind, this data, // like all local models and data can be manipulated by the user, so it // should not be relied upon for security or authorization.
// Grab the encoded data from the meta tag userConfigEncoded = document.querySelector('head meta[name=app-user-config]').attr('content');
// Unescape the text, then parse the resulting JSON into a real object userConfig = JSON.parse(unescape(userConfigEncoded));
// Lookup the store store = application.lookup('service:store');
// Push the encoded JSON into the store store.pushPayload(userConfig); }
export default { name: 'named-instance-initializer', initialize }; ```
instanceInitializer
Parameter instanceInitializer
Modifiers
@public
property instanceInitializers
static instanceInitializers: Record<string, Initializer<EngineInstance>>;
property Resolver
Resolver: ResolverClass;
Set this to provide an alternate class to
DefaultResolver
resolver
Modifiers
@public
method buildInstance
buildInstance: (options?: EngineInstanceOptions) => EngineInstance;
Create an EngineInstance for this engine.
buildInstance {EngineInstance} the engine instance
Modifiers
@public
method buildRegistry
static buildRegistry: (namespace: Engine) => Registry;
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 theirtarget
andcontrollers
properties all controllers receive the application as theirnamespace
property the application view receives the application controller as itscontroller
property the application view receives the application template as itsdefaultTemplate
propertybuildRegistry
Parameter namespace
the application for which to build the registry {Ember.Registry} the built registry
Build and configure the registry for the current engine.
buildRegistry {Ember.Registry} the configured registry
method ensureInitializers
ensureInitializers: () => void;
Ensure that initializers are run once, and only once, per engine.
ensureInitializers
method init
init: (properties: object | undefined) => void;
method initializer
initializer: (initializer: Initializer<Engine>) => void;
initializer
method instanceInitializer
instanceInitializer: (initializer: Initializer<EngineInstance>) => void;
instanceInitializer
method runInitializers
runInitializers: () => void;
runInitializers
method runInstanceInitializers
runInstanceInitializers: <T extends EngineInstance>(instance: T) => void;
1.12.0 runInstanceInitializers
interface Engine
interface Engine extends RegistryProxyMixin {}
The
Engine
class contains core functionality for both applications and engines.Each engine manages a registry that's used for dependency injection and exposed through
RegistryProxy
.Engines also manage initializers and instance initializers.
Engines can spawn
EngineInstance
instances viabuildInstance()
.Engine Ember.Namespace RegistryProxyMixin
Modifiers
@public
interface Initializer
interface Initializer<T> {}
property after
after?: string | string[];
property before
before?: string | string[];
property initialize
initialize: (target: T) => void;
property name
name: string;
namespace @ember/engine/instance
module '@ember/engine/instance' {}
class EngineInstance
class EngineInstance extends EngineInstance_base {}
property [ENGINE_PARENT]
[ENGINE_PARENT]?: EngineInstance;
property application
application: Application;
property base
base: Engine;
The base
Engine
for which this is an instance.{Engine} engine
property mountPoint
mountPoint?: string;
property routable
routable?: boolean;
method boot
boot: (options?: BootOptions) => Promise<this>;
Initialize the
EngineInstance
and return a promise that resolves with the instance itself when the boot process is complete.The primary task here is to run any registered instance initializers.
See the documentation on
BootOptions
for the options it takes.boot
Parameter options
{Promise<EngineInstance,Error>}
Modifiers
@public
method buildChildEngineInstance
buildChildEngineInstance: ( name: string, options?: EngineInstanceOptions) => EngineInstance;
Build a new
EngineInstance
that's a child of this instance.Engines must be registered by name with their parent engine (or application).
buildChildEngineInstance
Parameter name
the registered name of the engine.
Parameter options
options provided to the engine instance. {EngineInstance,Error}
method cloneParentDependencies
cloneParentDependencies: () => void;
Clone dependencies shared between an engine instance and its parent.
cloneParentDependencies
method init
init: (properties: object | undefined) => void;
method setupRegistry
static setupRegistry: (_registry: Registry, _options?: BootOptions) => void;
setupRegistry
Parameter registry
Parameter options
method unregister
unregister: (fullName: FullName) => void;
Unregister a factory.
Overrides
RegistryProxy#unregister
in order to clear any cached instances of the unregistered factory.unregister
Parameter fullName
Modifiers
@public
interface BootOptions
interface BootOptions {}
property document
document?: Document | null;
property isBrowser
isBrowser?: boolean;
property isInteractive
isInteractive?: boolean;
property location
location?: string | null;
property rootElement
rootElement?: string | SimpleElement | null;
property shouldRender
shouldRender?: boolean;
interface EngineInstance
interface EngineInstance extends RegistryProxyMixin, ContainerProxyMixin, InternalOwner, Owner {}
The
EngineInstance
encapsulates all of the stateful aspects of a runningEngine
.EngineInstance EmberObject RegistryProxyMixin ContainerProxyMixin
Modifiers
@public
interface EngineInstanceOptions
interface EngineInstanceOptions {}
property mountPoint
mountPoint?: string;
property routable
routable?: boolean;
namespace @ember/engine/lib/engine-parent
module '@ember/engine/lib/engine-parent' {}
variable ENGINE_PARENT
const ENGINE_PARENT: Symbol;
function getEngineParent
getEngineParent: (engine: EngineInstance) => EngineInstance | undefined;
getEngineParent
retrieves an engine instance's parent instance.getEngineParent
Parameter engine
An engine instance. {EngineInstance} The parent engine instance. @ember/engine
function setEngineParent
setEngineParent: (engine: EngineInstance, parent: EngineInstance) => void;
setEngineParent
sets an engine instance's parent instance.setEngineParent
Parameter engine
An engine instance.
Parameter parent
The parent engine instance.
namespace @ember/engine/parent
module '@ember/engine/parent' {}
variable ENGINE_PARENT
const ENGINE_PARENT: Symbol;
function getEngineParent
getEngineParent: (engine: EngineInstance) => EngineInstance | undefined;
getEngineParent
retrieves an engine instance's parent instance.getEngineParent
Parameter engine
An engine instance. {EngineInstance} The parent engine instance. @ember/engine
function setEngineParent
setEngineParent: (engine: EngineInstance, parent: EngineInstance) => void;
setEngineParent
sets an engine instance's parent instance.setEngineParent
Parameter engine
An engine instance.
Parameter parent
The parent engine instance.
namespace @ember/enumerable
module '@ember/enumerable' {}
variable Enumerable
const Enumerable: Mixin;
interface Enumerable
interface Enumerable {}
The methods in this mixin have been moved to [MutableArray](/ember/release/classes/MutableArray). This mixin has been intentionally preserved to avoid breaking Enumerable.detect checks until the community migrates away from them.
Enumerable
namespace @ember/enumerable/mutable
module '@ember/enumerable/mutable' {}
variable MutableEnumerable
const MutableEnumerable: Mixin;
interface MutableEnumerable
interface MutableEnumerable extends Enumerable {}
The methods in this mixin have been moved to MutableArray. This mixin has been intentionally preserved to avoid breaking MutableEnumerable.detect checks until the community migrates away from them.
MutableEnumerable Ember Enumerable
namespace @ember/helper
module '@ember/helper' {}
variable array
const array: ArrayHelper;
Using the
{{array}}
helper, you can pass arrays directly from the template as an argument to your components.import { array } from '@ember/helper';<template><ul>{{#each (array 'Tom Dale' 'Yehuda Katz' @anotherPerson) as |person|}}<li>{{person}}</li>{{/each}}</ul></template>**NOTE:** this example uses the experimental `<template>` feature, which isthe only place you need to import `array` to use it (it is a built-in whenwriting standalone `.hbs` files).
variable capabilities
const capabilities: any;
capabilities
returns a capabilities configuration which can be used to modify the behavior of the manager. Manager capabilities _must_ be provided using thecapabilities
function, as the underlying implementation can change over time.The first argument to capabilities is a version string, which is the version of Ember that the capabilities were defined in. Ember can add new versions at any time, and these may have entirely different behaviors, but it will not remove old versions until the next major version.
```js capabilities('3.23'); ```
The second argument is an object of capabilities and boolean values indicating whether they are enabled or disabled.
```js capabilities('3.23', { hasValue: true, hasDestructor: true, }); ```
If no value is specified, then the default value will be used.
###
3.23
capabilities####
hasDestroyable
- Default value: false
Determines if the helper has a destroyable to include in the destructor hierarchy. If enabled, the
getDestroyable
hook will be called, and its result will be associated with the destroyable parent block.####
hasValue
- Default value: false
Determines if the helper has a value which can be used externally. The helper's
getValue
hook will be run whenever the value of the helper is accessed if this capability is enabled.capabilities @ember/helper
Parameter managerApiVersion
The version of capabilities that are being used
Parameter options
The capabilities values {Capabilities} The capabilities object instance
Modifiers
@public
variable concat
const concat: ConcatHelper;
The
{{concat}}
helper makes it easy to dynamically send a number of parameters to a component or helper as a single parameter in the format of a concatenated string.For example:
import { concat } from '@ember/helper';<template>{{get @foo (concat "item" @index)}}</template>This will display the result of
@foo.item1
whenindex
is1
, andthis.foo.item2
whenindex
is2
, etc.**NOTE:** this example uses the experimental
<template>
feature, which is the only place you need to importconcat
to use it (it is a built-in when writing standalone.hbs
files).
variable fn
const fn: FnHelper;
{{fn}}
is a helper that receives a function and some arguments, and returns a new function that combines. This allows you to pass parameters along to functions in your templates:import { fn } from '@ember/helper';function showAlert(message) {alert(`The message is: '${message}'`);}<template><button type="button" {{on "click" (fn showAlert "Hello!")}}>Click me!</button></template>
variable get
const get: GetHelper;
The
{{get}}
helper makes it easy to dynamically look up a property on an object or an element in an array. The second argument to{{get}}
can be a string or a number, depending on the object being accessed.To access a property on an object with a string key:
import { get } from '@ember/helper';<template>{{get @someObject "objectKey"}}</template>To access the first element in an array:
import { get } from '@ember/helper';<template>{{get @someArray 0}}</template>To access a property on an object with a dynamic key:
import { get } from '@ember/helper';<template>{{get @address @field}}</template>This will display the result of
@foo.item1
whenindex
is1
, andthis.foo.item2
whenindex
is2
, etc.**NOTE:** this example uses the experimental
<template>
feature, which is the only place you need to importconcat
to use it (it is a built-in when writing standalone.hbs
files).
variable hash
const hash: HashHelper;
Using the
{{hash}}
helper, you can pass objects directly from the template as an argument to your components.import { hash } from '@ember/helper';<template>{{#each-in (hash givenName='Jen' familyName='Weber') as |key value|}}<p>{{key}}: {{value}}</p>{{/each-in}}</template>**NOTE:** this example uses the experimental
<template>
feature, which is the only place you need to importhash
to use it (it is a built-in when writing standalone.hbs
files).
variable invokeHelper
const invokeHelper: any;
The
invokeHelper
function can be used to create a helper instance in JavaScript.To access a helper's value you have to use
getValue
from@glimmer/tracking/primitives/cache
.```js // app/components/data-loader.js import Component from '@glimmer/component'; import { getValue } from '@glimmer/tracking/primitives/cache'; import Helper from '@ember/component/helper'; import { invokeHelper } from '@ember/helper';
class PlusOne extends Helper { compute([number]) { return number + 1; } }
export default class PlusOneComponent extends Component { plusOne = invokeHelper(this, PlusOne, () => { return { positional: [this.args.number], }; });
get value() { return getValue(this.plusOne); } } ``` ```js {{this.value}} ```
It receives three arguments:
context
: The parent context of the helper. When the parent is torn down and removed, the helper will be as well.definition
: The definition of the helper.computeArgs
: An optional function that produces the arguments to the helper. The function receives the parent context as an argument, and must return an object with apositional
property that is an array and/or anamed
property that is an object.And it returns a Cache instance that contains the most recent value of the helper. You can access the helper using
getValue()
like any other cache. The cache is also destroyable, and using thedestroy()
function on it will cause the helper to be torn down.Note that using
getValue()
on helpers that have scheduled effects will not trigger the effect early. Effects will continue to run at their scheduled time.invokeHelper @ember/helper
Parameter context
The parent context of the helper
Parameter definition
The helper definition
Parameter computeArgs
An optional function that produces args
Returns
Modifiers
@public
variable setHelperManager
const setHelperManager: any;
Sets the helper manager for an object or function.
```js setHelperManager((owner) => new ClassHelperManager(owner), Helper) ```
When a value is used as a helper in a template, the helper manager is looked up on the object by walking up its prototype chain and finding the first helper manager. This manager then receives the value and can create and manage an instance of a helper from it. This provides a layer of indirection that allows users to design high-level helper APIs, without Ember needing to worry about the details. High-level APIs can be experimented with and iterated on while the core of Ember helpers remains stable, and new APIs can be introduced gradually over time to existing code bases.
setHelperManager
receives two arguments:1. A factory function, which receives the
owner
and returns an instance of a helper manager. 2. A helper definition, which is the object or function to associate the factory function with.The first time the object is looked up, the factory function will be called to create the helper manager. It will be cached, and in subsequent lookups the cached helper manager will be used instead.
Only one helper manager is guaranteed to exist per
owner
and per usage ofsetHelperManager
, so many helpers will end up using the same instance of the helper manager. As such, you should only store state that is related to the manager itself. If you want to store state specific to a particular helper definition, you should assign a unique helper manager to that helper. In general, most managers should either be stateless, or only have theowner
they were created with as state.Helper managers must fulfill the following interface (This example uses [TypeScript interfaces](https://www.typescriptlang.org/docs/handbook/interfaces.html) for precision, you do not need to write helper managers using TypeScript):
```ts interface HelperManager { capabilities: HelperCapabilities;
createHelper(definition: HelperDefinition, args: TemplateArgs): HelperStateBucket;
getValue?(bucket: HelperStateBucket): unknown;
runEffect?(bucket: HelperStateBucket): void;
getDestroyable?(bucket: HelperStateBucket): object; } ```
The capabilities property _must_ be provided using the
capabilities()
function imported from the same module assetHelperManager
:```js import { capabilities } from '@ember/helper';
class MyHelperManager { capabilities = capabilities('3.21.0', { hasValue: true });
// ...snip... } ```
Below is a description of each of the methods on the interface and their functions.
####
createHelper
createHelper
is a required hook on the HelperManager interface. The hook is passed the definition of the helper that is currently being created, and is expected to return a _state bucket_. This state bucket is what represents the current state of the helper, and will be passed to the other lifecycle hooks at appropriate times. It is not necessarily related to the definition of the helper itself - for instance, you could return an object _containing_ an instance of the helper:```js class MyManager { createHelper(Definition, args) { return { instance: new Definition(args); }; } } ```
This allows the manager to store metadata that it doesn't want to expose to the user.
This hook is _not_ autotracked - changes to tracked values used within this hook will _not_ result in a call to any of the other lifecycle hooks. This is because it is unclear what should happen if it invalidates, and rather than make a decision at this point, the initial API is aiming to allow as much expressivity as possible. This could change in the future with changes to capabilities and their behaviors.
If users do want to autotrack some values used during construction, they can either create the instance of the helper in
runEffect
orgetValue
, or they can use thecache
API to autotrack thecreateHelper
hook themselves. This provides maximum flexibility and expressiveness to manager authors.This hook has the following timing semantics:
*Always** - called as discovered during DOM construction - called in definition order in the template
####
getValue
getValue
is an optional hook that should return the value of the helper. This is the value that is returned from the helper and passed into the template.This hook is called when the value is requested from the helper (e.g. when the template is rendering and the helper value is needed). The hook is autotracked, and will rerun whenever any tracked values used inside of it are updated. Otherwise it does not rerun.
> Note: This means that arguments which are not _consumed_ within the hook will > not trigger updates.
This hook is only called for helpers with the
hasValue
capability enabled. This hook has the following timing semantics:*Always** - called the first time the helper value is requested - called after autotracked state has changed
*Never** - called if the
hasValue
capability is disabled####
runEffect
runEffect
is an optional hook that should run the effect that the helper is applying, setting it up or updating it.This hook is scheduled to be called some time after render and prior to paint. There is not a guaranteed, 1-to-1 relationship between a render pass and this hook firing. For instance, multiple render passes could occur, and the hook may only trigger once. It may also never trigger if it was dirtied in one render pass and then destroyed in the next.
The hook is autotracked, and will rerun whenever any tracked values used inside of it are updated. Otherwise it does not rerun.
The hook is also run during a time period where state mutations are _disabled_ in Ember. Any tracked state mutation will throw an error during this time, including changes to tracked properties, changes made using
Ember.set
, updates to computed properties, etc. This is meant to prevent infinite rerenders and other antipatterns.This hook is only called for helpers with the
hasScheduledEffect
capability enabled. This hook is also not called in SSR currently, though this could be added as a capability in the future. It has the following timing semantics:*Always** - called after the helper was first created, if the helper has not been destroyed since creation - called after autotracked state has changed, if the helper has not been destroyed during render
*Never** - called if the
hasScheduledEffect
capability is disabled - called in SSR####
getDestroyable
getDestroyable
is an optional hook that users can use to register a destroyable object for the helper. This destroyable will be registered to the containing block or template parent, and will be destroyed when it is destroyed. See the [Destroyables RFC](https://github.com/emberjs/rfcs/blob/master/text/0580-destroyables.md) for more details.getDestroyable
is only called if thehasDestroyable
capability is enabled.This hook has the following timing semantics:
*Always** - called immediately after the
createHelper
hook is called*Never** - called if the
hasDestroyable
capability is disabledsetHelperManager @ember/helper
Parameter factory
A factory function which receives an optional owner, and returns a helper manager
Parameter definition
The definition to associate the manager factory with {object} The definition passed into setHelperManager
Modifiers
@public
variable uniqueId
const uniqueId: () => string;
Use the {{uniqueId}} helper to generate a unique ID string suitable for use as an ID attribute in the DOM.
Each invocation of {{uniqueId}} will return a new, unique ID string. You can use the
let
helper to create an ID that can be reused within a template.import { uniqueId } from '@ember/helper';<template>{{#let (uniqueId) as |emailId|}}<label for={{emailId}}>Email address</label><input id={{emailId}} type="email" />{{/let}}</template>
interface ArrayHelper
interface ArrayHelper extends Opaque<'helper:array'> {}
interface ConcatHelper
interface ConcatHelper extends Opaque<'helper:concat'> {}
interface FnHelper
interface FnHelper extends Opaque<'helper:fn'> {}
interface GetHelper
interface GetHelper extends Opaque<'helper:get'> {}
interface HashHelper
interface HashHelper extends Opaque<'helper:hash'> {}
type UniqueIdHelper
type UniqueIdHelper = typeof uniqueId;
namespace @ember/instrumentation
module '@ember/instrumentation' {}
variable subscribers
let subscribers: Subscriber<any>[];
The purpose of the Ember Instrumentation module is to provide efficient, general-purpose instrumentation for Ember.
Subscribe to a listener by using
subscribe
:```javascript import { subscribe } from '@ember/instrumentation';
subscribe("render", { before(name, timestamp, payload) {
},
after(name, timestamp, payload) {
} }); ```
If you return a value from the
before
callback, that same value will be passed as a fourth parameter to theafter
callback.Instrument a block of code by using
instrument
:```javascript import { instrument } from '@ember/instrumentation';
instrument("render.handlebars", payload, function() { // rendering logic }, binding); ```
Event names passed to
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 withrender
. It would receive callbacks for events namedrender
,render.handlebars
,render.container
, or evenrender.handlebars.layout
.Instrumentation
function flaggedInstrument
flaggedInstrument: <Result>( _name: string, _payload: object, callback: () => Result) => Result;
function instrument
instrument: { <Result>(name: string, callback: InstrumentCallback<undefined, Result>): Result; <Binding, Result>( name: string, callback: InstrumentCallback<Binding, Result>, binding: Binding ): Result; <Result>( name: string, payload: object, callback: InstrumentCallback<undefined, Result> ): Result; <Binding, Result>( name: string, payload: object, callback: InstrumentCallback<Binding, Result>, binding: Binding ): Result;};
Notifies event's subscribers, calls
before
andafter
hooks.instrument @ember/instrumentation
Parameter name
Namespaced event name.
Parameter payload
Parameter callback
Function that you're instrumenting.
Parameter binding
Context that instrument function is called with.
function reset
reset: () => void;
Resets
Instrumentation
by flushing list of subscribers.reset @ember/instrumentation
function subscribe
subscribe: <T>(pattern: string, object: Listener<T>) => Subscriber<T>;
Subscribes to a particular event or instrumented block of code.
subscribe @ember/instrumentation
Parameter pattern
Namespaced event name.
Parameter object
Before and After hooks.
{Subscriber}
function unsubscribe
unsubscribe: (subscriber: Subscriber<any>) => void;
Unsubscribes from a particular event or instrumented block of code.
unsubscribe @ember/instrumentation
Parameter subscriber
interface Listener
interface Listener<T> {}
interface PayloadWithException
interface PayloadWithException {}
property exception
exception?: any;
interface StructuredProfilePayload
interface StructuredProfilePayload {}
property object
object: string | object;
interface Subscriber
interface Subscriber<T> {}
namespace @ember/modifier
module '@ember/modifier' {}
variable on
const on: OnModifier;
function setModifierManager
setModifierManager: <T extends object>( factory: (owner: Owner) => ModifierManager<unknown>, modifier: T) => T;
interface OnModifier
interface OnModifier extends Opaque<'modifier:on'> {}
namespace @ember/modifier/on
module '@ember/modifier/on' {}
variable on
const on: OnModifier;
interface OnModifier
interface OnModifier extends Opaque<'modifier:on'> {}
namespace @ember/object
module '@ember/object' {}
function action
action: { ( target: ElementDescriptor[0], key: ElementDescriptor[1], desc: ElementDescriptor[2] ): PropertyDescriptor; (desc: PropertyDescriptor): ExtendedMethodDecorator;};
function computed
computed: { ( target: object, propertyName: string, descriptor: DecoratorPropertyDescriptor ): DecoratorPropertyDescriptor | void; (...dependentKeys: string[]): ComputedDecorator; (...args: ComputedDecoratorKeysAndConfig): ComputedDecorator; (callback: ComputedPropertyCallback): ComputedDecorator;};
This helper returns a new property descriptor that wraps the passed computed property function. You can use this helper to define properties with native decorator syntax, mixins, or via
defineProperty()
.Example:
```js import { computed, set } from '@ember/object';
class Person { constructor() { this.firstName = 'Betty'; this.lastName = 'Jones'; },
@computed('firstName', 'lastName') get fullName() { return
${this.firstName} ${this.lastName}
; } }let client = new Person();
client.fullName; // 'Betty Jones'
set(client, 'lastName', 'Fuller'); client.fullName; // 'Betty Fuller' ```
Classic Class Example:
```js import EmberObject, { computed } from '@ember/object';
let Person = EmberObject.extend({ init() { this._super(...arguments);
this.firstName = 'Betty'; this.lastName = 'Jones'; },
fullName: computed('firstName', 'lastName', function() { return
${this.get('firstName')} ${this.get('lastName')}
; }) });let client = Person.create();
client.get('fullName'); // 'Betty Jones'
client.set('lastName', 'Fuller'); client.get('fullName'); // 'Betty Fuller' ```
You can also provide a setter, either directly on the class using native class syntax, or by passing a hash with
get
andset
functions.Example:
```js import { computed, set } from '@ember/object';
class Person { constructor() { this.firstName = 'Betty'; this.lastName = 'Jones'; },
@computed('firstName', 'lastName') get fullName() { return
${this.firstName} ${this.lastName}
; }set fullName(value) { let [firstName, lastName] = value.split(/\s+/);
set(this, 'firstName', firstName); set(this, 'lastName', lastName);
return value; } }
let client = new Person();
client.fullName; // 'Betty Jones'
set(client, 'lastName', 'Fuller'); client.fullName; // 'Betty Fuller' ```
Classic Class Example:
```js import EmberObject, { computed } from '@ember/object';
let Person = EmberObject.extend({ init() { this._super(...arguments);
this.firstName = 'Betty'; this.lastName = 'Jones'; },
fullName: computed('firstName', 'lastName', { get(key) { return
${this.get('firstName')} ${this.get('lastName')}
; }, set(key, value) { let [firstName, lastName] = value.split(/\s+/); this.setProperties({ firstName, lastName }); return value; } }) });let client = Person.create(); client.get('firstName'); // 'Betty'
client.set('fullName', 'Carroll Fuller'); client.get('firstName'); // 'Carroll' ```
When passed as an argument, the
set
function should accept two parameters,key
andvalue
. The value returned fromset
will be the new value of the property._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](https://guides.emberjs.com/release/configuring-ember/disabling-prototype-extensions/) enabled._
computed @ember/object
Parameter dependentKeys
Optional dependent keys that trigger this computed property.
Parameter func
The computed property function. {ComputedDecorator} property decorator instance
Modifiers
@public
function defineProperty
defineProperty: ( obj: object, keyName: string, desc?: ExtendedMethodDecorator | PropertyDescriptor | undefined | null, data?: any | undefined | null, _meta?: Meta) => void;
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
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 import { defineProperty, computed } from '@ember/object';
// ES5 compatible mode defineProperty(contact, 'firstName', { writable: true, configurable: false, enumerable: true, value: 'Charles' });
// define a simple property defineProperty(contact, 'lastName', undefined, 'Jolley');
// define a computed property defineProperty(contact, 'fullName', computed('firstName', 'lastName', function() { return this.firstName+' '+this.lastName; })); ```
defineProperty @ember/object
Parameter obj
the object to define this property on. This may be a prototype.
Parameter keyName
the name of the property
Parameter desc
an instance of
Descriptor
(typically a computed property) or an ES5 descriptor. You must provide this ordata
but not both.Parameter data
something other than a descriptor, that will become the explicit value of this property.
Modifiers
@public
function get
get: { <T extends object, K extends keyof T>(obj: T, keyName: K): T[K]; (obj: unknown, keyName: string): unknown;};
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.```javascript import { get } from '@ember/object'; get(obj, "name"); ```
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.get @ember/object
Parameter obj
The object to retrieve from.
Parameter keyName
The property key to retrieve {Object} the property value or
null
.Modifiers
@public
function getProperties
getProperties: { <T, K extends keyof T>(obj: T, list: K[]): Pick<T, K>; <T, K extends keyof T>(obj: T, ...list: K[]): Pick<T, K>; <K extends string>(obj: unknown, list: K[]): Record<K, unknown>; <K extends string>(obj: unknown, ...list: K[]): Record<K, unknown>;};
To get multiple properties at once, call
getProperties
with an object followed by a list of strings or an array:```javascript import { getProperties } from '@ember/object';
getProperties(record, 'firstName', 'lastName', 'zipCode'); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ```
is equivalent to:
```javascript import { getProperties } from '@ember/object';
getProperties(record, ['firstName', 'lastName', 'zipCode']); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ```
getProperties @ember/object
Parameter obj
Parameter list
of keys to get {Object}
Modifiers
@public
function notifyPropertyChange
notifyPropertyChange: ( obj: object, keyName: string, _meta?: Meta | null, value?: unknown) => void;
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.
notifyPropertyChange @ember/object
Parameter obj
The object with the property that will change
Parameter keyName
The property key (or path) that will change.
Parameter _meta
The objects meta.
Parameter value
The new value to set for the property {void} 3.1.0
Modifiers
@public
function observer
observer: <T extends AnyFn>( ...args: | [propertyName: string, ...additionalPropertyNames: string[], func: T] | [ObserverDefinition<T>]) => T;
Specify a method that observes property changes.
```javascript import EmberObject from '@ember/object'; import { observer } from '@ember/object';
export default EmberObject.extend({ valueObserver: observer('value', function() { // Executes whenever the "value" property changes }) }); ```
Also available as
Function.prototype.observes
if prototype extensions are enabled.observer @ember/object
Parameter propertyNames
*
Parameter func
func
Modifiers
@public
function set
set: <T>(obj: object, keyName: string, value: T, tolerant?: boolean) => T;
Sets the value of a property on an object, respecting computed properties and notifying observers and other listeners of the change. If the specified property is not defined on the object and the object implements the
setUnknownProperty
method, then instead of setting the value of the property on the object, itssetUnknownProperty
handler will be invoked with the two parameterskeyName
andvalue
.```javascript import { set } from '@ember/object'; set(obj, "name", value); ```
set @ember/object
Parameter obj
The object to modify.
Parameter keyName
The property key to set
Parameter value
The value to set {Object} the passed value.
Modifiers
@public
function setProperties
setProperties: { <T, K extends keyof T>(obj: T, properties: Pick<T, K>): Pick<T, K>; <T extends Record<string, unknown>>(obj: object, properties: T): T;};
Set a list of properties on an object. These properties are set inside a single
beginPropertyChanges
andendPropertyChanges
batch, so observers will be buffered.```javascript import EmberObject from '@ember/object'; let anObject = EmberObject.create();
anObject.setProperties({ firstName: 'Stanley', lastName: 'Stuart', age: 21 }); ```
setProperties @ember/object
Parameter obj
Parameter properties
properties
Modifiers
@public
function trySet
trySet: <T>(root: object, path: string, value: T) => T | undefined;
Error-tolerant form of
set
. Will not blow up if any part of the chain isundefined
,null
, or destroyed.This is primarily used when syncing bindings, which may try to update after an object has been destroyed.
```javascript import { trySet } from '@ember/object';
let obj = { name: "Zoey" }; trySet(obj, "contacts.twitter", "@emberjs"); ```
trySet @ember/object
Parameter root
The object to modify.
Parameter path
The property path to set
Parameter value
The value to set
Modifiers
@public
class EmberObject
class EmberObject extends EmberObject_base {}
interface EmberObject
interface EmberObject extends Observable {}
EmberObject
is the main base class for all Ember objects. It is a subclass ofCoreObject
with theObservable
mixin applied. For details, see the documentation for each of these.EmberObject CoreObject Observable
Modifiers
@public
namespace @ember/object/-internals
module '@ember/object/-internals' {}
variable FrameworkObject
let FrameworkObject: typeof EmberObject;
function cacheFor
cacheFor: { <T, K extends keyof T>(obj: T, key: K): T[K] | undefined; (obj: object, key: string): unknown;};
function guidFor
guidFor: (value: any | null | undefined) => string;
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,
EmberObject
-based or not.You can also use this method on DOM Element objects.
guidFor @ember/object/internals
Parameter obj
any object, string, number, Element, or primitive {String} the unique guid for this instance.
Modifiers
@public
interface FrameworkObject
interface FrameworkObject extends EmberObject {}
namespace @ember/object/compat
module '@ember/object/compat' {}
function dependentKeyCompat
dependentKeyCompat: { ( target: ElementDescriptor[0], key: ElementDescriptor[1], desc: ElementDescriptor[2] ): PropertyDescriptor; (desc: PropertyDescriptor): ExtendedMethodDecorator;};
@dependentKeyCompat
is decorator that can be used on _native getters_ that use tracked properties. It exposes the getter to Ember's classic computed property and observer systems, so they can watch it for changes. It can be used in both native and classic classes.Native Example:
```js import { tracked } from '@glimmer/tracking'; import { dependentKeyCompat } from '@ember/object/compat'; import { computed, set } from '@ember/object';
class Person { firstName; lastName;
get fullName() { return
${this.firstName} ${this.lastName}
; } }class Profile { constructor(person) { set(this, 'person', person); }
@computed('person.fullName') get helloMessage() { return
Hello, ${this.person.fullName}!
; } } ```Classic Example:
```js import { tracked } from '@glimmer/tracking'; import { dependentKeyCompat } from '@ember/object/compat'; import EmberObject, { computed, observer, set } from '@ember/object';
const Person = EmberObject.extend({ firstName: tracked(), lastName: tracked(),
fullName: dependentKeyCompat(function() { return
${this.firstName} ${this.lastName}
; }), });const Profile = EmberObject.extend({ person: null,
helloMessage: computed('person.fullName', function() { return
Hello, ${this.person.fullName}!
; }),onNameUpdated: observer('person.fullName', function() { console.log('person name updated!'); }), }); ```
dependentKeyCompat()
can receive a getter function or an object containingget
/set
methods when used in classic classes, like computed properties.In general, only properties which you _expect_ to be watched by older, untracked clases should be marked as dependency compatible. The decorator is meant as an interop layer for parts of Ember's older classic APIs, and should not be applied to every possible getter/setter in classes. The number of dependency compatible getters should be _minimized_ wherever possible. New application code should not need to use
@dependentKeyCompat
, since it is only for interoperation with older code.dependentKeyCompat @ember/object/compat
Parameter desc
A property descriptor containing the getter and setter (when used in classic classes) {PropertyDecorator} property decorator instance
Modifiers
@public
namespace @ember/object/computed
module '@ember/object/computed' {}
variable union
let union: ( dependentKey: string, ...additionalDependentKeys: string[]) => PropertyDecorator;
A computed property which returns a new array with all the unique elements from one or more dependent arrays.
Example:
```javascript import { set } from '@ember/object'; import { union } from '@ember/object/computed';
class Hamster { constructor(fruits, vegetables) { set(this, 'fruits', fruits); set(this, 'vegetables', vegetables); }
@union('fruits', 'vegetables') uniqueFruits; });
let hamster = new, Hamster( [ 'banana', 'grape', 'kale', 'banana', 'tomato' ], [ 'tomato', 'carrot', 'lettuce' ] );
hamster.uniqueFruits; // ['banana', 'grape', 'kale', 'tomato', 'carrot', 'lettuce'] ```
union @ember/object/computed
Parameter propertyKey
* {ComputedProperty} computes a new array with all the unique elements from one or more dependent arrays.
Modifiers
@public
function alias
alias: (altKey: string) => AliasDecorator;
function and
and: ( dependentKey: string, ...additionalDependentKeys: string[]) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that performs a logical
and
on the original values for the provided dependent properties.You may pass in more than two properties and even use property brace expansion. The computed property will return the first falsy value or last truthy value just like JavaScript's
&&
operator.Example:
```javascript import { set } from '@ember/object'; import { and } from '@ember/object/computed';
class Hamster { @and('hasTent', 'hasBackpack') readyForCamp; @and('hasWalkingStick', 'hasBackpack') readyForHike; }
let tomster = new Hamster();
tomster.readyForCamp; // false
set(tomster, 'hasTent', true); tomster.readyForCamp; // false
set(tomster, 'hasBackpack', true); tomster.readyForCamp; // true
set(tomster, 'hasBackpack', 'Yes'); tomster.readyForCamp; // 'Yes'
set(tomster, 'hasWalkingStick', null); tomster.readyForHike; // null ```
and @ember/object/computed
Parameter dependentKey
* {ComputedProperty} computed property which performs a logical
and
on the values of all the original values for properties.Modifiers
@public
function bool
bool: ( dependentKey: string) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that converts the provided dependent property into a boolean value.
Example:
```javascript import { set } from '@ember/object'; import { bool } from '@ember/object/computed';
class Hamster { @bool('numBananas') hasBananas }
let hamster = new Hamster();
hamster.hasBananas; // false
set(hamster, 'numBananas', 0); hamster.hasBananas; // false
set(hamster, 'numBananas', 1); hamster.hasBananas; // true
set(hamster, 'numBananas', null); hamster.hasBananas; // false ```
bool @ember/object/computed
Parameter dependentKey
{ComputedProperty} computed property which converts to boolean the original value for property
Modifiers
@public
function collect
collect: ( dependentKey: string, ...additionalDependentKeys: string[]) => PropertyDecorator;
A computed property that returns the array of values for the provided dependent properties.
Example:
```javascript import { set } from '@ember/object'; import { collect } from '@ember/object/computed';
class Hamster { @collect('hat', 'shirt') clothes; }
let hamster = new Hamster();
hamster.clothes; // [null, null]
set(hamster, 'hat', 'Camp Hat'); set(hamster, 'shirt', 'Camp Shirt'); hamster.clothes; // ['Camp Hat', 'Camp Shirt'] ```
collect @ember/object/computed
Parameter dependentKey
* {ComputedProperty} computed property which maps values of all passed in properties to an array.
Modifiers
@public
function deprecatingAlias
deprecatingAlias: ( dependentKey: string, options: DeprecationOptions) => import('@ember/-internals/metal').ComputedDecorator;
Creates a new property that is an alias for another property on an object. Calls to
get
orset
this property behave as though they were called on the original property, but also print a deprecation warning.Example:
```javascript import { set } from '@ember/object'; import { deprecatingAlias } from '@ember/object/computed';
class Hamster { @deprecatingAlias('cavendishCount', { id: 'hamster.deprecate-banana', until: '3.0.0' }) bananaCount; }
let hamster = new Hamster();
set(hamster, 'bananaCount', 5); // Prints a deprecation warning. hamster.cavendishCount; // 5 ```
deprecatingAlias @ember/object/computed
Parameter dependentKey
Parameter options
Options for
deprecate
. {ComputedProperty} computed property which creates an alias with a deprecation to the original value for property. 1.7.0Modifiers
@public
function empty
empty: ( dependentKey: string) => import('@ember/-internals/metal').ComputedDecorator;
A computed property macro that returns true if the value of the dependent property is null, an empty string, empty array, or empty function.
Example:
```javascript import { set } from '@ember/object'; import { empty } from '@ember/object/computed';
class ToDoList { constructor(todos) { set(this, 'todos', todos); }
@empty('todos') isDone; }
let todoList = new ToDoList( ['Unit Test', 'Documentation', 'Release'] );
todoList.isDone; // false set(todoList, 'todos', []); todoList.isDone; // true ```
1.6.0 empty @ember/object/computed
Parameter dependentKey
{ComputedProperty} computed property which returns true if the value of the dependent property is null, an empty string, empty array, or empty function and false if the underlying value is not empty.
Modifiers
@public
function equal
equal: ( dependentKey: string, value: unknown) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that returns true if the provided dependent property is equal to the given value.
Example:
```javascript import { set } from '@ember/object'; import { equal } from '@ember/object/computed';
class Hamster { @equal('percentCarrotsEaten', 100) satisfied; }
let hamster = new Hamster();
hamster.satisfied; // false
set(hamster, 'percentCarrotsEaten', 100); hamster.satisfied; // true
set(hamster, 'percentCarrotsEaten', 50); hamster.satisfied; // false ```
equal @ember/object/computed
Parameter dependentKey
Parameter value
{ComputedProperty} computed property which returns true if the original value for property is equal to the given value.
Modifiers
@public
function expandProperties
expandProperties: ( pattern: string, callback: (expansion: string) => void) => void;
Expands
pattern
, invokingcallback
for each expansion.The only pattern supported is brace-expansion, anything else will be passed once to
callback
directly.Example
```js import { expandProperties } from '@ember/object/computed';
function echo(arg){ console.log(arg); }
expandProperties('foo.bar', echo); //=> 'foo.bar' expandProperties('{foo,bar}', echo); //=> 'foo', 'bar' expandProperties('foo.{bar,baz}', echo); //=> 'foo.bar', 'foo.baz' expandProperties('{foo,bar}.baz', echo); //=> 'foo.baz', 'bar.baz' expandProperties('foo.{bar,baz}.[]', echo) //=> 'foo.bar.[]', 'foo.baz.[]' expandProperties('{foo,bar}.{spam,eggs}', echo) //=> 'foo.spam', 'foo.eggs', 'bar.spam', 'bar.eggs' expandProperties('{foo}.bar.{baz}') //=> 'foo.bar.baz' ```
expandProperties @ember/object/computed
Parameter pattern
The property pattern to expand.
Parameter callback
The callback to invoke. It is invoked once per expansion, and is passed the expansion.
Modifiers
@public
function filter
filter: { ( dependentKey: string, callback: ( value: unknown, index: number, array: unknown[] | EmberArray<unknown> ) => unknown ): PropertyDecorator; ( dependentKey: string, additionalDependentKeys: string[], callback: ( value: unknown, index: number, array: unknown[] | EmberArray<unknown> ) => unknown ): PropertyDecorator;};
Filters the array by the callback, like the
Array.prototype.filter
method.The callback method you provide should have the following signature: -
item
is the current item in the iteration. -index
is the integer index of the current item in the iteration. -array
is the dependant array itself.```javascript function filterCallback(item, index, array); ```
In the callback, return a truthy value that coerces to true to keep the element, or a falsy to reject it.
Example:
```javascript import { set } from '@ember/object'; import { filter } from '@ember/object/computed';
class Hamster { constructor(chores) { set(this, 'chores', chores); }
@filter('chores', function(chore, index, array) { return !chore.done; }) remainingChores; }
let hamster = Hamster.create([ { name: 'cook', done: true }, { name: 'clean', done: true }, { name: 'write more unit tests', done: false } ]);
hamster.remainingChores; // [{name: 'write more unit tests', done: false}] ```
You can also use
@each.property
in your dependent key, the callback will still use the underlying array:```javascript import { set } from '@ember/object'; import { filter } from '@ember/object/computed';
class Hamster { constructor(chores) { set(this, 'chores', chores); }
@filter('chores.@each.done', function(chore, index, array) { return !chore.done; }) remainingChores; }
let hamster = new Hamster([ { name: 'cook', done: true }, { name: 'clean', done: true }, { name: 'write more unit tests', done: false } ]); hamster.remainingChores; // [{name: 'write more unit tests', done: false}]
set(hamster.chores[2], 'done', true); hamster.remainingChores; // [] ```
Finally, you can optionally pass an array of additional dependent keys as the second parameter to the macro, if your filter function relies on any external values:
```javascript import { filter } from '@ember/object/computed';
class Hamster { constructor(chores) { set(this, 'chores', chores); }
doneKey = 'finished';
@filter('chores', ['doneKey'], function(chore, index, array) { return !chore[this.doneKey]; }) remainingChores; }
let hamster = new Hamster([ { name: 'cook', finished: true }, { name: 'clean', finished: true }, { name: 'write more unit tests', finished: false } ]);
hamster.remainingChores; // [{name: 'write more unit tests', finished: false}] ```
filter @ember/object/computed
Parameter dependentKey
Parameter additionalDependentKeys
optional array of additional dependent keys
Parameter callback
{ComputedProperty} the filtered array
Modifiers
@public
function filterBy
filterBy: ( dependentKey: string, propertyKey: string, value?: unknown) => PropertyDecorator;
Filters the array by the property and value.
Example:
```javascript import { set } from '@ember/object'; import { filterBy } from '@ember/object/computed';
class Hamster { constructor(chores) { set(this, 'chores', chores); }
@filterBy('chores', 'done', false) remainingChores; }
let hamster = new Hamster([ { name: 'cook', done: true }, { name: 'clean', done: true }, { name: 'write more unit tests', done: false } ]);
hamster.remainingChores; // [{ name: 'write more unit tests', done: false }] ```
filterBy @ember/object/computed
Parameter dependentKey
Parameter propertyKey
Parameter value
{ComputedProperty} the filtered array
Modifiers
@public
function gt
gt: ( dependentKey: string, value: number) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that returns true if the provided dependent property is greater than the provided value.
Example:
```javascript import { set } from '@ember/object'; import { gt } from '@ember/object/computed';
class Hamster { @gt('numBananas', 10) hasTooManyBananas; }
let hamster = new Hamster();
hamster.hasTooManyBananas; // false
set(hamster, 'numBananas', 3); hamster.hasTooManyBananas; // false
set(hamster, 'numBananas', 11); hamster.hasTooManyBananas; // true ```
gt @ember/object/computed
Parameter dependentKey
Parameter value
{ComputedProperty} computed property which returns true if the original value for property is greater than given value.
Modifiers
@public
function gte
gte: ( dependentKey: string, value: number) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that returns true if the provided dependent property is greater than or equal to the provided value.
Example:
```javascript import { set } from '@ember/object'; import { gte } from '@ember/object/computed';
class Hamster { @gte('numBananas', 10) hasTooManyBananas; }
let hamster = new Hamster();
hamster.hasTooManyBananas; // false
set(hamster, 'numBananas', 3); hamster.hasTooManyBananas; // false
set(hamster, 'numBananas', 10); hamster.hasTooManyBananas; // true ```
gte @ember/object/computed
Parameter dependentKey
Parameter value
{ComputedProperty} computed property which returns true if the original value for property is greater or equal then given value.
Modifiers
@public
function intersect
intersect: ( dependentKey: string, ...additionalDependentKeys: string[]) => PropertyDecorator;
A computed property which returns a new array with all the elements two or more dependent arrays have in common.
Example:
```javascript import { set } from '@ember/object'; import { intersect } from '@ember/object/computed';
class FriendGroups { constructor(adaFriends, charlesFriends) { set(this, 'adaFriends', adaFriends); set(this, 'charlesFriends', charlesFriends); }
@intersect('adaFriends', 'charlesFriends') friendsInCommon; }
let groups = new FriendGroups( ['Charles Babbage', 'John Hobhouse', 'William King', 'Mary Somerville'], ['William King', 'Mary Somerville', 'Ada Lovelace', 'George Peacock'] );
groups.friendsInCommon; // ['William King', 'Mary Somerville'] ```
intersect @ember/object/computed
Parameter propertyKey
* {ComputedProperty} computes a new array with all the duplicated elements from the dependent arrays
Modifiers
@public
function lt
lt: ( dependentKey: string, value: number) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that returns true if the provided dependent property is less than the provided value.
Example:
```javascript import { set } from '@ember/object'; import { lt } from '@ember/object/computed';
class Hamster { @lt('numBananas', 3) needsMoreBananas; }
let hamster = new Hamster();
hamster.needsMoreBananas; // true
set(hamster, 'numBananas', 3); hamster.needsMoreBananas; // false
set(hamster, 'numBananas', 2); hamster.needsMoreBananas; // true ```
lt @ember/object/computed
Parameter dependentKey
Parameter value
{ComputedProperty} computed property which returns true if the original value for property is less then given value.
Modifiers
@public
function lte
lte: ( dependentKey: string, value: number) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that returns true if the provided dependent property is less than or equal to the provided value.
Example:
```javascript import { set } from '@ember/object'; import { lte } from '@ember/object/computed';
class Hamster { @lte('numBananas', 3) needsMoreBananas; }
let hamster = new Hamster();
hamster.needsMoreBananas; // true
set(hamster, 'numBananas', 5); hamster.needsMoreBananas; // false
set(hamster, 'numBananas', 3); hamster.needsMoreBananas; // true ```
lte @ember/object/computed
Parameter dependentKey
Parameter value
{ComputedProperty} computed property which returns true if the original value for property is less or equal than given value.
Modifiers
@public
function map
map: { ( dependentKey: string, callback: (value: unknown, index: number) => unknown ): PropertyDecorator; ( dependentKey: string, additionalDependentKeys: string[], callback: (value: unknown, index: number) => unknown ): PropertyDecorator;};
Returns an array mapped via the callback
The callback method you provide should have the following signature: -
item
is the current item in the iteration. -index
is the integer index of the current item in the iteration.```javascript function mapCallback(item, index); ```
Example:
```javascript import { set } from '@ember/object'; import { map } from '@ember/object/computed';
class Hamster { constructor(chores) { set(this, 'chores', chores); }
@map('chores', function(chore, index) { return
${chore.toUpperCase()}!
; }) excitingChores; });let hamster = new Hamster(['clean', 'write more unit tests']);
hamster.excitingChores; // ['CLEAN!', 'WRITE MORE UNIT TESTS!'] ```
You can optionally pass an array of additional dependent keys as the second parameter to the macro, if your map function relies on any external values:
```javascript import { set } from '@ember/object'; import { map } from '@ember/object/computed';
class Hamster { shouldUpperCase = false;
constructor(chores) { set(this, 'chores', chores); }
@map('chores', ['shouldUpperCase'], function(chore, index) { if (this.shouldUpperCase) { return
${chore.toUpperCase()}!
; } else { return${chore}!
; } }) excitingChores; }let hamster = new Hamster(['clean', 'write more unit tests']);
hamster.excitingChores; // ['clean!', 'write more unit tests!']
set(hamster, 'shouldUpperCase', true); hamster.excitingChores; // ['CLEAN!', 'WRITE MORE UNIT TESTS!'] ```
map @ember/object/computed
Parameter dependentKey
Parameter additionalDependentKeys
optional array of additional dependent keys
Parameter callback
{ComputedProperty} an array mapped via the callback
Modifiers
@public
function mapBy
mapBy: (dependentKey: string, propertyKey: string) => PropertyDecorator;
Returns an array mapped to the specified key.
Example:
```javascript import { set } from '@ember/object'; import { mapBy } from '@ember/object/computed';
class Person { children = [];
@mapBy('children', 'age') childAges; }
let lordByron = new Person();
lordByron.childAges; // []
set(lordByron, 'children', [ { name: 'Augusta Ada Byron', age: 7 } ]); lordByron.childAges; // [7]
set(lordByron, 'children', [ ...lordByron.children, { name: 'Allegra Byron', age: 5 }, { name: 'Elizabeth Medora Leigh', age: 8 } ]); lordByron.childAges; // [7, 5, 8] ```
mapBy @ember/object/computed
Parameter dependentKey
Parameter propertyKey
{ComputedProperty} an array mapped to the specified key
Modifiers
@public
function match
match: ( dependentKey: string, regexp: RegExp) => import('@ember/-internals/metal').ComputedDecorator;
A computed property which matches the original value for the dependent property against a given RegExp, returning
true
if the value matches the RegExp andfalse
if it does not.Example:
```javascript import { set } from '@ember/object'; import { match } from '@ember/object/computed';
class User { @match('email', /^.+@.+..+$/) hasValidEmail; }
let user = new User();
user.hasValidEmail; // false
set(user, 'email', ''); user.hasValidEmail; // false
set(user, 'email', 'ember_hamster@example.com'); user.hasValidEmail; // true ```
match @ember/object/computed
Parameter dependentKey
Parameter regexp
{ComputedProperty} computed property which match the original value for property against a given RegExp
Modifiers
@public
function max
max: (dependentKey: string) => PropertyDecorator;
A computed property that calculates the maximum value in the dependent array. This will return
-Infinity
when the dependent array is empty.Example:
```javascript import { set } from '@ember/object'; import { mapBy, max } from '@ember/object/computed';
class Person { children = [];
@mapBy('children', 'age') childAges; @max('childAges') maxChildAge; }
let lordByron = new Person();
lordByron.maxChildAge; // -Infinity
set(lordByron, 'children', [ { name: 'Augusta Ada Byron', age: 7 } ]); lordByron.maxChildAge; // 7
set(lordByron, 'children', [ ...lordByron.children, { name: 'Allegra Byron', age: 5 }, { name: 'Elizabeth Medora Leigh', age: 8 } ]); lordByron.maxChildAge; // 8 ```
If the types of the arguments are not numbers, they will be converted to numbers and the type of the return value will always be
Number
. For example, the max of a list of Date objects will be the highest timestamp as aNumber
. This behavior is consistent withMath.max
.max @ember/object/computed
Parameter dependentKey
{ComputedProperty} computes the largest value in the dependentKey's array
Modifiers
@public
function min
min: (dependentKey: string) => PropertyDecorator;
A computed property that calculates the minimum value in the dependent array. This will return
Infinity
when the dependent array is empty.Example:
```javascript import { set } from '@ember/object'; import { mapBy, min } from '@ember/object/computed';
class Person { children = [];
@mapBy('children', 'age') childAges; @min('childAges') minChildAge; }
let lordByron = Person.create({ children: [] });
lordByron.minChildAge; // Infinity
set(lordByron, 'children', [ { name: 'Augusta Ada Byron', age: 7 } ]); lordByron.minChildAge; // 7
set(lordByron, 'children', [ ...lordByron.children, { name: 'Allegra Byron', age: 5 }, { name: 'Elizabeth Medora Leigh', age: 8 } ]); lordByron.minChildAge; // 5 ```
If the types of the arguments are not numbers, they will be converted to numbers and the type of the return value will always be
Number
. For example, the min of a list of Date objects will be the lowest timestamp as aNumber
. This behavior is consistent withMath.min
.min @ember/object/computed
Parameter dependentKey
{ComputedProperty} computes the smallest value in the dependentKey's array
Modifiers
@public
function none
none: ( dependentKey: string) => import('@ember/-internals/metal').ComputedDecorator;
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.
```javascript import { set } from '@ember/object'; import { none } from '@ember/object/computed';
class Hamster { @none('food') isHungry; }
let hamster = new Hamster();
hamster.isHungry; // true
set(hamster, 'food', 'Banana'); hamster.isHungry; // false
set(hamster, 'food', null); hamster.isHungry; // true ```
none @ember/object/computed
Parameter dependentKey
{ComputedProperty} computed property which returns true if original value for property is null or undefined.
Modifiers
@public
function not
not: ( dependentKey: string) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that returns the inverse boolean value of the original value for the dependent property.
Example:
```javascript import { set } from '@ember/object'; import { not } from '@ember/object/computed';
class User { loggedIn = false;
@not('loggedIn') isAnonymous; }
let user = new User();
user.isAnonymous; // true set(user, 'loggedIn', true); user.isAnonymous; // false ```
not @ember/object/computed
Parameter dependentKey
{ComputedProperty} computed property which returns inverse of the original value for property
Modifiers
@public
function notEmpty
notEmpty: ( dependentKey: string) => import('@ember/-internals/metal').ComputedDecorator;
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 import { set } from '@ember/object'; import { notEmpty } from '@ember/object/computed';
class Hamster { constructor(backpack) { set(this, 'backpack', backpack); }
@notEmpty('backpack') hasStuff }
let hamster = new Hamster( ['Food', 'Sleeping Bag', 'Tent'] );
hamster.hasStuff; // true set(hamster, 'backpack', []); hamster.hasStuff; // false ```
notEmpty @ember/object/computed
Parameter dependentKey
{ComputedProperty} computed property which returns true if original value for property is not empty.
Modifiers
@public
function oneWay
oneWay: (dependentKey: string) => PropertyDecorator;
Where the
alias
computed macro aliasesget
andset
, and allows for bidirectional data flow, theoneWay
computed macro only provides an aliasedget
. Theset
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 import { set } from '@ember/object'; import { oneWay }from '@ember/object/computed';
class User { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@oneWay('firstName') nickName; }
let teddy = new User('Teddy', 'Zeenny');
teddy.nickName; // 'Teddy'
set(teddy, 'nickName', 'TeddyBear'); teddy.firstName; // 'Teddy' teddy.nickName; // 'TeddyBear' ```
oneWay @ember/object/computed
Parameter dependentKey
{ComputedProperty} computed property which creates a one way computed property to the original value for property.
Modifiers
@public
function or
or: ( dependentKey: string, ...additionalDependentKeys: string[]) => import('@ember/-internals/metal').ComputedDecorator;
A computed property which performs a logical
or
on the original values for the provided dependent properties.You may pass in more than two properties and even use property brace expansion. The computed property will return the first truthy value or last falsy value just like JavaScript's
||
operator.Example:
```javascript import { set } from '@ember/object'; import { or } from '@ember/object/computed';
class Hamster { @or('hasJacket', 'hasUmbrella') readyForRain; @or('hasSunscreen', 'hasUmbrella') readyForBeach; }
let tomster = new Hamster();
tomster.readyForRain; // undefined
set(tomster, 'hasUmbrella', true); tomster.readyForRain; // true
set(tomster, 'hasJacket', 'Yes'); tomster.readyForRain; // 'Yes'
set(tomster, 'hasSunscreen', 'Check'); tomster.readyForBeach; // 'Check' ```
or @ember/object/computed
Parameter dependentKey
* {ComputedProperty} computed property which performs a logical
or
on the values of all the original values for properties.Modifiers
@public
function readOnly
readOnly: (dependentKey: string) => PropertyDecorator;
Where
oneWay
computed macro provides oneWay bindings, thereadOnly
computed macro provides a readOnly one way binding. Very often when using theoneWay
macro 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 import { set } from '@ember/object'; import { readOnly } from '@ember/object/computed';
class User { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@readOnly('firstName') nickName; });
let teddy = new User('Teddy', 'Zeenny');
teddy.nickName; // 'Teddy'
set(teddy, 'nickName', 'TeddyBear'); // throws Exception // throw new EmberError('Cannot Set: nickName on: <User:ember27288>' );`
teddy.firstName; // 'Teddy' ```
readOnly @ember/object/computed
Parameter dependentKey
{ComputedProperty} computed property which creates a one way computed property to the original value for property. 1.5.0
Modifiers
@public
function reads
reads: (dependentKey: string) => PropertyDecorator;
Where the
alias
computed macro aliasesget
andset
, and allows for bidirectional data flow, theoneWay
computed macro only provides an aliasedget
. Theset
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 import { set } from '@ember/object'; import { oneWay }from '@ember/object/computed';
class User { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@oneWay('firstName') nickName; }
let teddy = new User('Teddy', 'Zeenny');
teddy.nickName; // 'Teddy'
set(teddy, 'nickName', 'TeddyBear'); teddy.firstName; // 'Teddy' teddy.nickName; // 'TeddyBear' ```
oneWay @ember/object/computed
Parameter dependentKey
{ComputedProperty} computed property which creates a one way computed property to the original value for property.
Modifiers
@public
function setDiff
setDiff: (setAProperty: string, setBProperty: string) => PropertyDecorator;
A computed property which returns a new array with all the properties from the first dependent array that are not in the second dependent array.
Example:
```javascript import { set } from '@ember/object'; import { setDiff } from '@ember/object/computed';
class Hamster { constructor(likes, fruits) { set(this, 'likes', likes); set(this, 'fruits', fruits); }
@setDiff('likes', 'fruits') wants; }
let hamster = new Hamster( [ 'banana', 'grape', 'kale' ], [ 'grape', 'kale', ] );
hamster.wants; // ['banana'] ```
setDiff @ember/object/computed
Parameter setAProperty
Parameter setBProperty
{ComputedProperty} computes a new array with all the items from the first dependent array that are not in the second dependent array
Modifiers
@public
function sort
sort: { (itemsKey: string, sortDefinition: SortDefinition | string): PropertyDecorator; ( itemsKey: string, additionalDependentKeys: string[], sortDefinition: SortDefinition ): PropertyDecorator;};
A computed property which returns a new array with all the properties from the first dependent array sorted based on a property or sort function. The sort macro can be used in two different ways:
1. By providing a sort callback function 2. By providing an array of keys to sort the array
In the first form, the callback method you provide should have the following signature:
```javascript function sortCallback(itemA, itemB); ```
-
itemA
the first item to compare. -itemB
the second item to compare.This function should return negative number (e.g.
-1
) whenitemA
should come beforeitemB
. It should return positive number (e.g.1
) whenitemA
should come afteritemB
. If theitemA
anditemB
are equal this function should return0
.Therefore, if this function is comparing some numeric values, simple `itemA - itemB
or
itemA.get( 'foo' ) - itemB.get( 'foo' )` can be used instead of series ofif
.Example:
```javascript import { set } from '@ember/object'; import { sort } from '@ember/object/computed';
class ToDoList { constructor(todos) { set(this, 'todos', todos); }
// using a custom sort function @sort('todos', function(a, b){ if (a.priority > b.priority) { return 1; } else if (a.priority < b.priority) { return -1; }
return 0; }) priorityTodos; }
let todoList = new ToDoList([ { name: 'Unit Test', priority: 2 }, { name: 'Documentation', priority: 3 }, { name: 'Release', priority: 1 } ]);
todoList.priorityTodos; // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }] ```
You can also optionally pass an array of additional dependent keys as the second parameter, if your sort function is dependent on additional values that could changes:
```js import EmberObject, { set } from '@ember/object'; import { sort } from '@ember/object/computed';
class ToDoList { sortKey = 'priority';
constructor(todos) { set(this, 'todos', todos); }
// using a custom sort function @sort('todos', ['sortKey'], function(a, b){ if (a[this.sortKey] > b[this.sortKey]) { return 1; } else if (a[this.sortKey] < b[this.sortKey]) { return -1; }
return 0; }) sortedTodos; });
let todoList = new ToDoList([ { name: 'Unit Test', priority: 2 }, { name: 'Documentation', priority: 3 }, { name: 'Release', priority: 1 } ]);
todoList.priorityTodos; // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }] ```
In the second form, you should provide the key of the array of sort values as the second parameter:
```javascript import { set } from '@ember/object'; import { sort } from '@ember/object/computed';
class ToDoList { constructor(todos) { set(this, 'todos', todos); }
// using standard ascending sort todosSorting = ['name']; @sort('todos', 'todosSorting') sortedTodos;
// using descending sort todosSortingDesc = ['name:desc']; @sort('todos', 'todosSortingDesc') sortedTodosDesc; }
let todoList = new ToDoList([ { name: 'Unit Test', priority: 2 }, { name: 'Documentation', priority: 3 }, { name: 'Release', priority: 1 } ]);
todoList.sortedTodos; // [{ name:'Documentation', priority:3 }, { name:'Release', priority:1 }, { name:'Unit Test', priority:2 }] todoList.sortedTodosDesc; // [{ name:'Unit Test', priority:2 }, { name:'Release', priority:1 }, { name:'Documentation', priority:3 }] ```
sort @ember/object/computed
Parameter itemsKey
Parameter sortDefinitionOrDependentKeys
The key of the sort definition (an array of sort properties), the sort function, or an array of additional dependent keys
Parameter sortDefinition
the sort function (when used with additional dependent keys) {ComputedProperty} computes a new sorted array based on the sort property array or callback function
Modifiers
@public
function sum
sum: (dependentKey: string) => PropertyDecorator;
A computed property that returns the sum of the values in the dependent array.
Example:
```javascript import { sum } from '@ember/object/computed';
class Invoice { lineItems = [1.00, 2.50, 9.99];
@sum('lineItems') total; }
let invoice = new Invoice();
invoice.total; // 13.49 ```
sum @ember/object/computed
Parameter dependentKey
{ComputedProperty} computes the sum of all values in the dependentKey's array 1.4.0
Modifiers
@public
function uniq
uniq: ( dependentKey: string, ...additionalDependentKeys: string[]) => PropertyDecorator;
A computed property which returns a new array with all the unique elements from one or more dependent arrays.
Example:
```javascript import { set } from '@ember/object'; import { uniq } from '@ember/object/computed';
class Hamster { constructor(fruits) { set(this, 'fruits', fruits); }
@uniq('fruits') uniqueFruits; }
let hamster = new Hamster([ 'banana', 'grape', 'kale', 'banana' ]);
hamster.uniqueFruits; // ['banana', 'grape', 'kale'] ```
uniq @ember/object/computed
Parameter propertyKey
* {ComputedProperty} computes a new array with all the unique elements from the dependent array
Modifiers
@public
function uniqBy
uniqBy: (dependentKey: string, propertyKey: string) => PropertyDecorator;
A computed property which returns a new array with all the unique elements from an array, with uniqueness determined by specific key.
Example:
```javascript import { set } from '@ember/object'; import { uniqBy } from '@ember/object/computed';
class Hamster { constructor(fruits) { set(this, 'fruits', fruits); }
@uniqBy('fruits', 'id') uniqueFruits; }
let hamster = new Hamster([ { id: 1, 'banana' }, { id: 2, 'grape' }, { id: 3, 'peach' }, { id: 1, 'banana' } ]);
hamster.uniqueFruits; // [ { id: 1, 'banana' }, { id: 2, 'grape' }, { id: 3, 'peach' }] ```
uniqBy @ember/object/computed
Parameter dependentKey
Parameter propertyKey
{ComputedProperty} computes a new array with all the unique elements from the dependent array
Modifiers
@public
class ComputedProperty
class ComputedProperty extends ComputedDescriptor {}
@computed
is a decorator that turns a JavaScript getter and setter into a computed property, which is a _cached, trackable value_. By default the getter 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 cleared if the dependencies are modified, and lazily recomputed the next time something asks for it.In the following example we decorate a getter -
fullName
- by callingcomputed
with the property dependencies (firstName
andlastName
) as arguments. ThefullName
getter will be called once (regardless of how many times it is accessed) as long as its dependencies do not change. OncefirstName
orlastName
are updated any future calls tofullName
will incorporate the new values, and any watchers of the value such as templates will be updated:```javascript import { computed, set } from '@ember/object';
class Person { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@computed('firstName', 'lastName') get fullName() { return
${this.firstName} ${this.lastName}
; } });let tom = new Person('Tom', 'Dale');
tom.fullName; // 'Tom Dale' ```
You can also provide a setter, which will be used when updating the computed property. Ember's
set
function must be used to update the property since it will also notify observers of the property:```javascript import { computed, set } from '@ember/object';
class Person { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@computed('firstName', 'lastName') get fullName() { return
${this.firstName} ${this.lastName}
; }set fullName(value) { let [firstName, lastName] = value.split(' ');
set(this, 'firstName', firstName); set(this, 'lastName', lastName); } });
let person = new Person();
set(person, 'fullName', 'Peter Wagenet'); person.firstName; // 'Peter' person.lastName; // 'Wagenet' ```
You can also pass a getter function or object with
get
andset
functions as the last argument to the computed decorator. This allows you to define computed property _macros_:```js import { computed } from '@ember/object';
function join(...keys) { return computed(...keys, function() { return keys.map(key => this[key]).join(' '); }); }
class Person { @join('firstName', 'lastName') fullName; } ```
Note that when defined this way, getters and setters receive the _key_ of the property they are decorating as the first argument. Setters receive the value they are setting to as the second argument instead. Additionally, setters must _return_ the value that should be cached:
```javascript import { computed, set } from '@ember/object';
function fullNameMacro(firstNameKey, lastNameKey) { return computed(firstNameKey, lastNameKey, { get() { return
${this[firstNameKey]} ${this[lastNameKey]}
; }set(key, value) { let [firstName, lastName] = value.split(' ');
set(this, firstNameKey, firstName); set(this, lastNameKey, lastName);
return value; } }); }
class Person { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@fullNameMacro('firstName', 'lastName') fullName; });
let person = new Person();
set(person, 'fullName', 'Peter Wagenet'); person.firstName; // 'Peter' person.lastName; // 'Wagenet' ```
Computed properties can also be used in classic classes. To do this, we provide the getter and setter as the last argument like we would for a macro, and we assign it to a property on the class definition. This is an _anonymous_ computed macro:
```javascript import EmberObject, { computed, set } from '@ember/object';
let Person = EmberObject.extend({ // these will be supplied by
create
firstName: null, lastName: null,fullName: computed('firstName', 'lastName', { get() { return
${this.firstName} ${this.lastName}
; }set(key, value) { let [firstName, lastName] = value.split(' ');
set(this, 'firstName', firstName); set(this, 'lastName', lastName);
return value; } }) });
let tom = Person.create({ firstName: 'Tom', lastName: 'Dale' });
tom.get('fullName') // 'Tom Dale' ```
You can overwrite computed property without setters with a normal property (no longer computed) that won't change if dependencies change. You can also mark computed property as
.readOnly()
and block all attempts to set it.```javascript import { computed, set } from '@ember/object';
class Person { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@computed('firstName', 'lastName').readOnly() get fullName() { return
${this.firstName} ${this.lastName}
; } });let person = new Person(); person.set('fullName', 'Peter Wagenet'); // Uncaught Error: Cannot set read-only property "fullName" on object: <(...):emberXXX> ```
Additional resources: - [Decorators RFC](https://github.com/emberjs/rfcs/blob/master/text/0408-decorators.md) - [New CP syntax RFC](https://github.com/emberjs/rfcs/blob/master/text/0011-improved-cp-syntax.md) - [New computed syntax explained in "Ember 1.12 released" ](https://emberjs.com/blog/2015/05/13/ember-1-12-released.html#toc_new-computed-syntax)
ComputedProperty
Modifiers
@public
constructor
constructor(args: (string | ComputedPropertyCallback)[]);
method get
get: (obj: object, keyName: string) => unknown;
method set
set: (obj: object, keyName: string, value: unknown) => unknown;
method setup
setup: ( obj: object, keyName: string, propertyDesc: DecoratorPropertyDescriptor, meta: Meta) => void;
method teardown
teardown: (obj: object, keyName: string, meta: Meta) => void;
namespace @ember/object/core
module '@ember/object/core' {}
class CoreObject
class CoreObject {}
constructor
constructor(owner?: Owner);
property concatenatedProperties
concatenatedProperties?: string | string[];
property isClass
static isClass: boolean;
property isDestroyed
isDestroyed: boolean;
Destroyed object property flag.
if this property is
true
the observers and bindings were already removed by the effect of calling thedestroy()
method.isDestroyed false
Modifiers
@public
property isDestroying
isDestroying: boolean;
Destruction scheduled flag. The
destroy()
method has been called.The object stays intact until the end of the run loop at which point the
isDestroyed
flag is set.isDestroying false
Modifiers
@public
property isMethod
static isMethod: boolean;
property mergedProperties
mergedProperties?: unknown[];
property PrototypeMixin
static readonly PrototypeMixin: any;
property superclass
static readonly superclass: any;
method create
static create: { <C extends typeof CoreObject>(this: C): InstanceType<C>; < C extends typeof CoreObject, I extends InstanceType<C>, K extends keyof I, Args extends Partial<{ [Key in K]: I[Key] }>[] >( this: C, ...args: Args ): InstanceType<C> & MergeArray<Args>;};
Creates an instance of a class. Accepts either no arguments, or an object containing values to initialize the newly instantiated object with.
```javascript import EmberObject from '@ember/object';
const Person = EmberObject.extend({ helloWorld() { alert(
Hi, my name is ${this.get('name')}
); } });let tom = Person.create({ name: 'Tom Dale' });
tom.helloWorld(); // alerts "Hi, my name is Tom Dale". ```
create
will call theinit
function if defined duringAnyObject.extend
If no arguments are passed to
create
, it will not set values to the new instance during initialization:```javascript let noName = Person.create(); noName.helloWorld(); // alerts undefined ```
NOTE: For performance reasons, you cannot declare methods or computed properties during
create
. You should instead declare methods and computed properties when usingextend
.create @ember/object
Parameter arguments
*
Modifiers
@public
method destroy
destroy: () => this;
Destroys an object by setting the
isDestroyed
flag and removing its metadata, which effectively destroys observers and bindings.If you try to set a property on a destroyed object, an exception will be raised.
Note that destruction is scheduled for the end of the run loop and does not happen immediately. It will set an isDestroying flag immediately.
destroy {EmberObject} receiver
Modifiers
@public
method detect
static detect: (obj: unknown) => boolean;
method detectInstance
static detectInstance: (obj: unknown) => boolean;
method eachComputedProperty
static eachComputedProperty: ( callback: (name: string, meta: unknown) => void, binding?: typeof CoreObject) => void;
Iterate over each computed property for the class, passing its name and any associated metadata (see
metaForProperty
) to the callback.eachComputedProperty
Parameter callback
Parameter binding
method extend
static extend: <Statics, Instance, M extends unknown[]>( this: Statics & EmberClassConstructor<Instance>, ...mixins: M) => Readonly<Statics> & EmberClassConstructor<Instance> & MergeArray<M>;
Creates a new subclass.
```javascript import EmberObject from '@ember/object';
const Person = EmberObject.extend({ say(thing) { alert(thing); } }); ```
This defines a new subclass of EmberObject:
Person
. It contains one method:say()
.You can also create a subclass from any existing class by calling its
extend()
method. For example, you might want to create a subclass of Ember's built-inComponent
class:```javascript import Component from '@ember/component';
const PersonComponent = Component.extend({ tagName: 'li', classNameBindings: ['isAdministrator'] }); ```
When defining a subclass, you can override methods but still access the implementation of your parent class by calling the special
_super()
method:```javascript import EmberObject from '@ember/object';
const Person = EmberObject.extend({ say(thing) { let name = this.get('name'); alert(
${name} says: ${thing}
); } });const Soldier = Person.extend({ say(thing) { this._super(
${thing}, sir!
); }, march(numberOfHours) { alert(${this.get('name')} marches for ${numberOfHours} hours.
); } });let yehuda = Soldier.create({ name: 'Yehuda Katz' });
yehuda.say('Yes'); // alerts "Yehuda Katz says: Yes, sir!" ```
The
create()
on line #17 creates an *instance* of theSoldier
class. Theextend()
on line #8 creates a *subclass* ofPerson
. Any instance of thePerson
class will *not* have themarch()
method.You can also pass
Mixin
classes to add additional properties to the subclass.```javascript import EmberObject from '@ember/object'; import Mixin from '@ember/object/mixin';
const Person = EmberObject.extend({ say(thing) { alert(
${this.get('name')} says: ${thing}
); } });const SingingMixin = Mixin.create({ sing(thing) { alert(
${this.get('name')} sings: la la la ${thing}
); } });const BroadwayStar = Person.extend(SingingMixin, { dance() { alert(
${this.get('name')} dances: tap tap tap tap
); } }); ```The
BroadwayStar
class contains three methods:say()
,sing()
, anddance()
.extend @ember/object
Parameter mixins
* One or more Mixin classes
Parameter arguments
* Object containing values to use within the new class
Modifiers
@public
method init
init: (_properties: object | undefined) => void;
An overridable method called when objects are instantiated. By default, does nothing unless it is overridden during class definition.
Example:
```javascript import EmberObject from '@ember/object';
const Person = EmberObject.extend({ init() { alert(
Name is ${this.get('name')}
); } });let steve = Person.create({ name: 'Steve' });
// alerts 'Name is Steve'. ```
NOTE: If you do override
init
for a framework class likeComponent
from@ember/component
, be sure to callthis._super(...arguments)
in yourinit
declaration! If you don't, Ember may not have an opportunity to do important setup work, and you'll see strange behavior in your application.init
Modifiers
@public
method metaForProperty
static metaForProperty: (key: string) => any;
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:
```javascript import { computed } from '@ember/object';
person: computed(function() { let personId = this.get('personId'); return Person.create({ id: personId }); }).meta({ type: Person }) ```
Once you've done this, you can retrieve the values saved to the computed property from your class like this:
```javascript MyClass.metaForProperty('person'); ```
This will return the original hash that was passed to
meta()
.metaForProperty
Parameter key
property name
method proto
static proto: () => CoreObject;
method reopen
static reopen: <C extends typeof CoreObject>(this: C, ...args: any[]) => C;
Augments a constructor's prototype with additional properties and functions:
```javascript import EmberObject from '@ember/object';
const MyObject = EmberObject.extend({ name: 'an object' });
o = MyObject.create(); o.get('name'); // 'an object'
MyObject.reopen({ say(msg) { console.log(msg); } });
o2 = MyObject.create(); o2.say('hello'); // logs "hello"
o.say('goodbye'); // logs "goodbye" ```
To add functions and properties to the constructor itself, see
reopenClass
reopen @ember/object
Modifiers
@public
method reopenClass
static reopenClass: <C extends typeof CoreObject>( this: C, ...mixins: Array<Mixin | Record<string, unknown>>) => C;
Augments a constructor's own properties and functions:
```javascript import EmberObject from '@ember/object';
const MyObject = EmberObject.extend({ name: 'an object' });
MyObject.reopenClass({ canBuild: false });
MyObject.canBuild; // false o = MyObject.create(); ```
In other words, this creates static properties and functions for the class. These are only available on the class and not on any instance of that class.
```javascript import EmberObject from '@ember/object';
const Person = EmberObject.extend({ name: '', sayHello() { alert(
Hello. My name is ${this.get('name')}
); } });Person.reopenClass({ species: 'Homo sapiens',
createPerson(name) { return Person.create({ name }); } });
let tom = Person.create({ name: 'Tom Dale' }); let yehuda = Person.createPerson('Yehuda Katz');
tom.sayHello(); // "Hello. My name is Tom Dale" yehuda.sayHello(); // "Hello. My name is Yehuda Katz" alert(Person.species); // "Homo sapiens" ```
Note that
species
andcreatePerson
are *not* valid on thetom
andyehuda
variables. They are only valid onPerson
.To add functions and properties to instances of a constructor by extending the constructor's prototype see
reopen
reopenClass @ember/object
Modifiers
@public
method toString
static toString: () => string;
Returns a string representation which attempts to provide more information than Javascript's
toString
typically does, in a generic way for all Ember objects.```javascript import EmberObject from '@ember/object';
const Person = EmberObject.extend(); person = Person.create(); person.toString(); //=> "<Person:ember1024>" ```
If the object's class is not defined on an Ember namespace, it will indicate it is a subclass of the registered superclass:
```javascript const Student = Person.extend(); let student = Student.create(); student.toString(); //=> "<(subclass of Person):ember1025>" ```
If the method
toStringExtension
is defined, its return value will be included in the output.```javascript const Teacher = Person.extend({ toStringExtension() { return this.get('fullName'); } }); teacher = Teacher.create(); teacher.toString(); //=> "<Teacher:ember1026:Tom Dale>" ```
toString {String} string representation
Modifiers
@public
method willDestroy
willDestroy: () => void;
Override to implement teardown.
willDestroy
Modifiers
@public
method willReopen
static willReopen: () => void;
interface CoreObject
interface CoreObject {}
CoreObject
is the base class for all Ember constructs. It establishes a class system based on Ember's Mixin system, and provides the basis for the Ember Object Model.CoreObject
should generally not be used directly, instead you should useEmberObject
.## Usage
You can define a class by extending from
CoreObject
using theextend
method:```js const Person = CoreObject.extend({ name: 'Tomster', }); ```
For detailed usage, see the [Object Model](https://guides.emberjs.com/release/object-model/) section of the guides.
## Usage with Native Classes
Native JavaScript
class
syntax can be used to extend from anyCoreObject
based class:```js class Person extends CoreObject { init() { super.init(...arguments); this.name = 'Tomster'; } } ```
Some notes about
class
usage:new
syntax is not currently supported with classes that extend fromEmberObject
orCoreObject
. You must continue to use thecreate
method when making new instances of classes, even if they are defined using native class syntax. If you want to usenew
syntax, consider creating classes which do _not_ extend fromEmberObject
orCoreObject
. Ember features, such as computed properties and decorators, will still work with base-less classes. Instead of usingthis._super()
, you must use standardsuper
syntax in native classes. See the [MDN docs on classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Super_class_calls_with_super) for more details. Native classes support using [constructors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Constructor) to set up newly-created instances. Ember uses these to, among other things, support features that need to retrieve other entities by name, like Service injection andgetOwner
. To ensure your custom instance setup logic takes place after this important work is done, avoid using theconstructor
in favor ofinit
. Properties passed tocreate
will be available on the instance by the timeinit
runs, so any code that requires these values should work at that time. Using native classes, and switching back to the old Ember Object model is fully supported.CoreObject
Modifiers
@public
namespace @ember/object/evented
module '@ember/object/evented' {}
variable Evented
const Evented: Mixin;
function on
on: <T extends AnyFn>(...args: [...eventNames: string[], func: T]) => T;
Define a property as a function that should be executed when a specified event or events are triggered.
``` javascript import EmberObject from '@ember/object'; import { on } from '@ember/object/evented'; import { sendEvent } from '@ember/object/events';
let Job = EmberObject.extend({ logCompleted: on('completed', function() { console.log('Job completed!'); }) });
let job = Job.create();
sendEvent(job, 'completed'); // Logs 'Job completed!' ```
on @ember/object/evented
Parameter eventNames
*
Parameter func
{Function} the listener function, passed as last argument to on(...)
Modifiers
@public
interface Evented
interface Evented {}
This mixin allows for Ember objects to subscribe to and emit events.
```app/utils/person.js import EmberObject from '@ember/object'; import Evented from '@ember/object/evented';
export default EmberObject.extend(Evented, { greet() { // ... this.trigger('greet'); } }); ```
```javascript var person = Person.create();
person.on('greet', function() { console.log('Our person has greeted'); });
person.greet();
// outputs: 'Our person has greeted' ```
You can also chain multiple event subscriptions:
```javascript person.on('greet', function() { console.log('Our person has greeted'); }).one('greet', function() { console.log('Offer one-time special'); }).off('event', this, forgetThis); ```
Evented
Modifiers
@public
method has
has: (name: string) => boolean;
Checks to see if object has any subscriptions for named event.
has
Parameter name
The name of the event {Boolean} does the object have a subscription for event
Modifiers
@public
method off
off: { <Target>( name: string, target: Target, method: string | ((this: Target, ...args: any[]) => void) ): this; (name: string, method: string | ((...args: any[]) => void)): this;};
Cancels subscription for given name, target, and method.
off
Parameter name
The name of the event
Parameter target
The target of the subscription
Parameter method
The function or the name of a function of the subscription this
Modifiers
@public
method on
on: { <Target>( name: string, target: Target, method: string | ((this: Target, ...args: any[]) => void) ): this; (name: string, method: string | ((...args: any[]) => void)): this;};
Subscribes to a named event with given function.
```javascript person.on('didLoad', function() { // fired once the person has loaded }); ```
An optional target can be passed in as the 2nd argument that will be set as the "this" for the callback. This is a good way to give your function access to the object triggering the event. When the target parameter is used the callback method becomes the third argument.
on
Parameter name
The name of the event
Parameter target
The "this" binding for the callback
Parameter method
A function or the name of a function to be called on
target
thisModifiers
@public
method one
one: { <Target>( name: string, target: Target, method: string | ((this: Target, ...args: any[]) => void) ): this; (name: string, method: string | ((...args: any[]) => void)): this;};
Subscribes a function to a named event and then cancels the subscription after the first time the event is triggered. It is good to use ``one`` when you only care about the first time an event has taken place.
This function takes an optional 2nd argument that will become the "this" value for the callback. When the target parameter is used the callback method becomes the third argument.
one
Parameter name
The name of the event
Parameter target
The "this" binding for the callback
Parameter method
A function or the name of a function to be called on
target
thisModifiers
@public
method trigger
trigger: (name: string, ...args: any[]) => any;
Triggers a named event for the object. Any additional arguments will be passed as parameters to the functions that are subscribed to the event.
```javascript person.on('didEat', function(food) { console.log('person ate some ' + food); });
person.trigger('didEat', 'broccoli');
// outputs: person ate some broccoli ```
trigger
Parameter name
The name of the event
Parameter args
Optional arguments to pass on
Modifiers
@public
namespace @ember/object/events
module '@ember/object/events' {}
function addListener
addListener: ( obj: object, eventName: string, target: object | Function | null, method?: Function | PropertyKey, once?: boolean, sync?: boolean) => void;
Add an event listener
addListener @ember/object/events
Parameter obj
Parameter eventName
Parameter target
A target object or a function
Parameter method
A function or the name of a function to be called on
target
Parameter once
A flag whether a function should only be called once
Modifiers
@public
function removeListener
removeListener: ( obj: object, eventName: string, targetOrFunction: object | Function | null, functionOrName?: string | Function) => void;
Remove an event listener
Arguments should match those passed to
addListener
.removeListener @ember/object/events
Parameter obj
Parameter eventName
Parameter target
A target object or a function
Parameter method
A function or the name of a function to be called on
target
Modifiers
@public
function sendEvent
sendEvent: ( obj: object, eventName: string, params?: any[], actions?: any[], _meta?: Meta | null) => boolean;
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.
sendEvent @ember/object/events
Parameter obj
Parameter eventName
Parameter params
Optional parameters for each listener. {Boolean} if the event was delivered to one or more actions
Modifiers
@public
namespace @ember/object/internals
module '@ember/object/internals' {}
function cacheFor
cacheFor: { <T, K extends keyof T>(obj: T, key: K): T[K] | undefined; (obj: object, key: string): unknown;};
function guidFor
guidFor: (value: any | null | undefined) => string;
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,
EmberObject
-based or not.You can also use this method on DOM Element objects.
guidFor @ember/object/internals
Parameter obj
any object, string, number, Element, or primitive {String} the unique guid for this instance.
Modifiers
@public
namespace @ember/object/lib/computed/computed_macros
module '@ember/object/lib/computed/computed_macros' {}
function and
and: ( dependentKey: string, ...additionalDependentKeys: string[]) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that performs a logical
and
on the original values for the provided dependent properties.You may pass in more than two properties and even use property brace expansion. The computed property will return the first falsy value or last truthy value just like JavaScript's
&&
operator.Example:
```javascript import { set } from '@ember/object'; import { and } from '@ember/object/computed';
class Hamster { @and('hasTent', 'hasBackpack') readyForCamp; @and('hasWalkingStick', 'hasBackpack') readyForHike; }
let tomster = new Hamster();
tomster.readyForCamp; // false
set(tomster, 'hasTent', true); tomster.readyForCamp; // false
set(tomster, 'hasBackpack', true); tomster.readyForCamp; // true
set(tomster, 'hasBackpack', 'Yes'); tomster.readyForCamp; // 'Yes'
set(tomster, 'hasWalkingStick', null); tomster.readyForHike; // null ```
and @ember/object/computed
Parameter dependentKey
* {ComputedProperty} computed property which performs a logical
and
on the values of all the original values for properties.Modifiers
@public
function bool
bool: ( dependentKey: string) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that converts the provided dependent property into a boolean value.
Example:
```javascript import { set } from '@ember/object'; import { bool } from '@ember/object/computed';
class Hamster { @bool('numBananas') hasBananas }
let hamster = new Hamster();
hamster.hasBananas; // false
set(hamster, 'numBananas', 0); hamster.hasBananas; // false
set(hamster, 'numBananas', 1); hamster.hasBananas; // true
set(hamster, 'numBananas', null); hamster.hasBananas; // false ```
bool @ember/object/computed
Parameter dependentKey
{ComputedProperty} computed property which converts to boolean the original value for property
Modifiers
@public
function deprecatingAlias
deprecatingAlias: ( dependentKey: string, options: DeprecationOptions) => import('@ember/-internals/metal').ComputedDecorator;
Creates a new property that is an alias for another property on an object. Calls to
get
orset
this property behave as though they were called on the original property, but also print a deprecation warning.Example:
```javascript import { set } from '@ember/object'; import { deprecatingAlias } from '@ember/object/computed';
class Hamster { @deprecatingAlias('cavendishCount', { id: 'hamster.deprecate-banana', until: '3.0.0' }) bananaCount; }
let hamster = new Hamster();
set(hamster, 'bananaCount', 5); // Prints a deprecation warning. hamster.cavendishCount; // 5 ```
deprecatingAlias @ember/object/computed
Parameter dependentKey
Parameter options
Options for
deprecate
. {ComputedProperty} computed property which creates an alias with a deprecation to the original value for property. 1.7.0Modifiers
@public
function empty
empty: ( dependentKey: string) => import('@ember/-internals/metal').ComputedDecorator;
A computed property macro that returns true if the value of the dependent property is null, an empty string, empty array, or empty function.
Example:
```javascript import { set } from '@ember/object'; import { empty } from '@ember/object/computed';
class ToDoList { constructor(todos) { set(this, 'todos', todos); }
@empty('todos') isDone; }
let todoList = new ToDoList( ['Unit Test', 'Documentation', 'Release'] );
todoList.isDone; // false set(todoList, 'todos', []); todoList.isDone; // true ```
1.6.0 empty @ember/object/computed
Parameter dependentKey
{ComputedProperty} computed property which returns true if the value of the dependent property is null, an empty string, empty array, or empty function and false if the underlying value is not empty.
Modifiers
@public
function equal
equal: ( dependentKey: string, value: unknown) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that returns true if the provided dependent property is equal to the given value.
Example:
```javascript import { set } from '@ember/object'; import { equal } from '@ember/object/computed';
class Hamster { @equal('percentCarrotsEaten', 100) satisfied; }
let hamster = new Hamster();
hamster.satisfied; // false
set(hamster, 'percentCarrotsEaten', 100); hamster.satisfied; // true
set(hamster, 'percentCarrotsEaten', 50); hamster.satisfied; // false ```
equal @ember/object/computed
Parameter dependentKey
Parameter value
{ComputedProperty} computed property which returns true if the original value for property is equal to the given value.
Modifiers
@public
function gt
gt: ( dependentKey: string, value: number) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that returns true if the provided dependent property is greater than the provided value.
Example:
```javascript import { set } from '@ember/object'; import { gt } from '@ember/object/computed';
class Hamster { @gt('numBananas', 10) hasTooManyBananas; }
let hamster = new Hamster();
hamster.hasTooManyBananas; // false
set(hamster, 'numBananas', 3); hamster.hasTooManyBananas; // false
set(hamster, 'numBananas', 11); hamster.hasTooManyBananas; // true ```
gt @ember/object/computed
Parameter dependentKey
Parameter value
{ComputedProperty} computed property which returns true if the original value for property is greater than given value.
Modifiers
@public
function gte
gte: ( dependentKey: string, value: number) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that returns true if the provided dependent property is greater than or equal to the provided value.
Example:
```javascript import { set } from '@ember/object'; import { gte } from '@ember/object/computed';
class Hamster { @gte('numBananas', 10) hasTooManyBananas; }
let hamster = new Hamster();
hamster.hasTooManyBananas; // false
set(hamster, 'numBananas', 3); hamster.hasTooManyBananas; // false
set(hamster, 'numBananas', 10); hamster.hasTooManyBananas; // true ```
gte @ember/object/computed
Parameter dependentKey
Parameter value
{ComputedProperty} computed property which returns true if the original value for property is greater or equal then given value.
Modifiers
@public
function lt
lt: ( dependentKey: string, value: number) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that returns true if the provided dependent property is less than the provided value.
Example:
```javascript import { set } from '@ember/object'; import { lt } from '@ember/object/computed';
class Hamster { @lt('numBananas', 3) needsMoreBananas; }
let hamster = new Hamster();
hamster.needsMoreBananas; // true
set(hamster, 'numBananas', 3); hamster.needsMoreBananas; // false
set(hamster, 'numBananas', 2); hamster.needsMoreBananas; // true ```
lt @ember/object/computed
Parameter dependentKey
Parameter value
{ComputedProperty} computed property which returns true if the original value for property is less then given value.
Modifiers
@public
function lte
lte: ( dependentKey: string, value: number) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that returns true if the provided dependent property is less than or equal to the provided value.
Example:
```javascript import { set } from '@ember/object'; import { lte } from '@ember/object/computed';
class Hamster { @lte('numBananas', 3) needsMoreBananas; }
let hamster = new Hamster();
hamster.needsMoreBananas; // true
set(hamster, 'numBananas', 5); hamster.needsMoreBananas; // false
set(hamster, 'numBananas', 3); hamster.needsMoreBananas; // true ```
lte @ember/object/computed
Parameter dependentKey
Parameter value
{ComputedProperty} computed property which returns true if the original value for property is less or equal than given value.
Modifiers
@public
function match
match: ( dependentKey: string, regexp: RegExp) => import('@ember/-internals/metal').ComputedDecorator;
A computed property which matches the original value for the dependent property against a given RegExp, returning
true
if the value matches the RegExp andfalse
if it does not.Example:
```javascript import { set } from '@ember/object'; import { match } from '@ember/object/computed';
class User { @match('email', /^.+@.+..+$/) hasValidEmail; }
let user = new User();
user.hasValidEmail; // false
set(user, 'email', ''); user.hasValidEmail; // false
set(user, 'email', 'ember_hamster@example.com'); user.hasValidEmail; // true ```
match @ember/object/computed
Parameter dependentKey
Parameter regexp
{ComputedProperty} computed property which match the original value for property against a given RegExp
Modifiers
@public
function none
none: ( dependentKey: string) => import('@ember/-internals/metal').ComputedDecorator;
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.
```javascript import { set } from '@ember/object'; import { none } from '@ember/object/computed';
class Hamster { @none('food') isHungry; }
let hamster = new Hamster();
hamster.isHungry; // true
set(hamster, 'food', 'Banana'); hamster.isHungry; // false
set(hamster, 'food', null); hamster.isHungry; // true ```
none @ember/object/computed
Parameter dependentKey
{ComputedProperty} computed property which returns true if original value for property is null or undefined.
Modifiers
@public
function not
not: ( dependentKey: string) => import('@ember/-internals/metal').ComputedDecorator;
A computed property that returns the inverse boolean value of the original value for the dependent property.
Example:
```javascript import { set } from '@ember/object'; import { not } from '@ember/object/computed';
class User { loggedIn = false;
@not('loggedIn') isAnonymous; }
let user = new User();
user.isAnonymous; // true set(user, 'loggedIn', true); user.isAnonymous; // false ```
not @ember/object/computed
Parameter dependentKey
{ComputedProperty} computed property which returns inverse of the original value for property
Modifiers
@public
function notEmpty
notEmpty: ( dependentKey: string) => import('@ember/-internals/metal').ComputedDecorator;
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 import { set } from '@ember/object'; import { notEmpty } from '@ember/object/computed';
class Hamster { constructor(backpack) { set(this, 'backpack', backpack); }
@notEmpty('backpack') hasStuff }
let hamster = new Hamster( ['Food', 'Sleeping Bag', 'Tent'] );
hamster.hasStuff; // true set(hamster, 'backpack', []); hamster.hasStuff; // false ```
notEmpty @ember/object/computed
Parameter dependentKey
{ComputedProperty} computed property which returns true if original value for property is not empty.
Modifiers
@public
function oneWay
oneWay: (dependentKey: string) => PropertyDecorator;
Where the
alias
computed macro aliasesget
andset
, and allows for bidirectional data flow, theoneWay
computed macro only provides an aliasedget
. Theset
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 import { set } from '@ember/object'; import { oneWay }from '@ember/object/computed';
class User { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@oneWay('firstName') nickName; }
let teddy = new User('Teddy', 'Zeenny');
teddy.nickName; // 'Teddy'
set(teddy, 'nickName', 'TeddyBear'); teddy.firstName; // 'Teddy' teddy.nickName; // 'TeddyBear' ```
oneWay @ember/object/computed
Parameter dependentKey
{ComputedProperty} computed property which creates a one way computed property to the original value for property.
Modifiers
@public
function or
or: ( dependentKey: string, ...additionalDependentKeys: string[]) => import('@ember/-internals/metal').ComputedDecorator;
A computed property which performs a logical
or
on the original values for the provided dependent properties.You may pass in more than two properties and even use property brace expansion. The computed property will return the first truthy value or last falsy value just like JavaScript's
||
operator.Example:
```javascript import { set } from '@ember/object'; import { or } from '@ember/object/computed';
class Hamster { @or('hasJacket', 'hasUmbrella') readyForRain; @or('hasSunscreen', 'hasUmbrella') readyForBeach; }
let tomster = new Hamster();
tomster.readyForRain; // undefined
set(tomster, 'hasUmbrella', true); tomster.readyForRain; // true
set(tomster, 'hasJacket', 'Yes'); tomster.readyForRain; // 'Yes'
set(tomster, 'hasSunscreen', 'Check'); tomster.readyForBeach; // 'Check' ```
or @ember/object/computed
Parameter dependentKey
* {ComputedProperty} computed property which performs a logical
or
on the values of all the original values for properties.Modifiers
@public
function readOnly
readOnly: (dependentKey: string) => PropertyDecorator;
Where
oneWay
computed macro provides oneWay bindings, thereadOnly
computed macro provides a readOnly one way binding. Very often when using theoneWay
macro 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 import { set } from '@ember/object'; import { readOnly } from '@ember/object/computed';
class User { constructor(firstName, lastName) { set(this, 'firstName', firstName); set(this, 'lastName', lastName); }
@readOnly('firstName') nickName; });
let teddy = new User('Teddy', 'Zeenny');
teddy.nickName; // 'Teddy'
set(teddy, 'nickName', 'TeddyBear'); // throws Exception // throw new EmberError('Cannot Set: nickName on: <User:ember27288>' );`
teddy.firstName; // 'Teddy' ```
readOnly @ember/object/computed
Parameter dependentKey
{ComputedProperty} computed property which creates a one way computed property to the original value for property. 1.5.0
Modifiers
@public
namespace @ember/object/lib/computed/reduce_computed_macros
module '@ember/object/lib/computed/reduce_computed_macros' {}
variable union
let union: ( dependentKey: string, ...additionalDependentKeys: string[]) => PropertyDecorator;
A computed property which returns a new array with all the unique elements from one or more dependent arrays.
Example:
```javascript import { set } from '@ember/object'; import { union } from '@ember/object/computed';
class Hamster { constructor(fruits, vegetables) { set(this, 'fruits', fruits); set(this, 'vegetables', vegetables); }
@union('fruits', 'vegetables') uniqueFruits; });
let hamster = new, Hamster( [ 'banana', 'grape', 'kale', 'banana', 'tomato' ], [ 'tomato', 'carrot', 'lettuce' ] );
hamster.uniqueFruits; // ['banana', 'grape', 'kale', 'tomato', 'carrot', 'lettuce'] ```
union @ember/object/computed
Parameter propertyKey
* {ComputedProperty} computes a new array with all the unique elements from one or more dependent arrays.
Modifiers
@public
function collect
collect: ( dependentKey: string, ...additionalDependentKeys: string[]) => PropertyDecorator;
A computed property that returns the array of values for the provided dependent properties.
Example:
```javascript import { set } from '@ember/object'; import { collect } from '@ember/object/computed';
class Hamster { @collect('hat', 'shirt') clothes; }
let hamster = new Hamster();
hamster.clothes; // [null, null]
set(hamster, 'hat', 'Camp Hat'); set(hamster, 'shirt', 'Camp Shirt'); hamster.clothes; // ['Camp Hat', 'Camp Shirt'] ```
collect @ember/object/computed
Parameter dependentKey
* {ComputedProperty} computed property which maps values of all passed in properties to an array.
Modifiers
@public
function filter
filter: { ( dependentKey: string, callback: ( value: unknown, index: number, array: unknown[] | EmberArray<unknown> ) => unknown ): PropertyDecorator; ( dependentKey: string, additionalDependentKeys: string[], callback: ( value: unknown, index: number, array: unknown[] | EmberArray<unknown> ) => unknown ): PropertyDecorator;};
Filters the array by the callback, like the
Array.prototype.filter
method.The callback method you provide should have the following signature: -
item
is the current item in the iteration. -index
is the integer index of the current item in the iteration. -array
is the dependant array itself.```javascript function filterCallback(item, index, array); ```
In the callback, return a truthy value that coerces to true to keep the element, or a falsy to reject it.
Example:
```javascript import { set } from '@ember/object'; import { filter } from '@ember/object/computed';
class Hamster { constructor(chores) { set(this, 'chores', chores); }
@filter('chores', function(chore, index, array) { return !chore.done; }) remainingChores; }
let hamster = Hamster.create([ { name: 'cook', done: true }, { name: 'clean', done: true }, { name: 'write more unit tests', done: false } ]);
hamster.remainingChores; // [{name: 'write more unit tests', done: false}] ```
You can also use
@each.property
in your dependent key, the callback will still use the underlying array:```javascript import { set } from '@ember/object'; import { filter } from '@ember/object/computed';
class Hamster { constructor(chores) { set(this, 'chores', chores); }
@filter('chores.@each.done', function(chore, index, array) { return !chore.done; }) remainingChores; }
let hamster = new Hamster([ { name: 'cook', done: true }, { name: 'clean', done: true }, { name: 'write more unit tests', done: false } ]); hamster.remainingChores; // [{name: 'write more unit tests', done: false}]
set(hamster.chores[2], 'done', true); hamster.remainingChores; // [] ```
Finally, you can optionally pass an array of additional dependent keys as the second parameter to the macro, if your filter function relies on any external values:
```javascript import { filter } from '@ember/object/computed';
class Hamster { constructor(chores) { set(this, 'chores', chores); }
doneKey = 'finished';
@filter('chores', ['doneKey'], function(chore, index, array) { return !chore[this.doneKey]; }) remainingChores; }
let hamster = new Hamster([ { name: 'cook', finished: true }, { name: 'clean', finished: true }, { name: 'write more unit tests', finished: false } ]);
hamster.remainingChores; // [{name: 'write more unit tests', finished: false}] ```
filter @ember/object/computed
Parameter dependentKey
Parameter additionalDependentKeys
optional array of additional dependent keys
Parameter callback
{ComputedProperty} the filtered array
Modifiers
@public
function filterBy
filterBy: ( dependentKey: string, propertyKey: string, value?: unknown) => PropertyDecorator;
Filters the array by the property and value.
Example:
```javascript import { set } from '@ember/object'; import { filterBy } from '@ember/object/computed';
class Hamster { constructor(chores) { set(this, 'chores', chores); }
@filterBy('chores', 'done', false) remainingChores; }
let hamster = new Hamster([ { name: 'cook', done: true }, { name: 'clean', done: true }, { name: 'write more unit tests', done: false } ]);
hamster.remainingChores; // [{ name: 'write more unit tests', done: false }] ```
filterBy @ember/object/computed
Parameter dependentKey
Parameter propertyKey
Parameter value
{ComputedProperty} the filtered array
Modifiers
@public
function intersect
intersect: ( dependentKey: string, ...additionalDependentKeys: string[]) => PropertyDecorator;
A computed property which returns a new array with all the elements two or more dependent arrays have in common.
Example:
```javascript import { set } from '@ember/object'; import { intersect } from '@ember/object/computed';
class FriendGroups { constructor(adaFriends, charlesFriends) { set(this, 'adaFriends', adaFriends); set(this, 'charlesFriends', charlesFriends); }
@intersect('adaFriends', 'charlesFriends') friendsInCommon; }
let groups = new FriendGroups( ['Charles Babbage', 'John Hobhouse', 'William King', 'Mary Somerville'], ['William King', 'Mary Somerville', 'Ada Lovelace', 'George Peacock'] );
groups.friendsInCommon; // ['William King', 'Mary Somerville'] ```
intersect @ember/object/computed
Parameter propertyKey
* {ComputedProperty} computes a new array with all the duplicated elements from the dependent arrays
Modifiers
@public
function map
map: { ( dependentKey: string, callback: (value: unknown, index: number) => unknown ): PropertyDecorator; ( dependentKey: string, additionalDependentKeys: string[], callback: (value: unknown, index: number) => unknown ): PropertyDecorator;};
Returns an array mapped via the callback
The callback method you provide should have the following signature: -
item
is the current item in the iteration. -index
is the integer index of the current item in the iteration.```javascript function mapCallback(item, index); ```
Example:
```javascript import { set } from '@ember/object'; import { map } from '@ember/object/computed';
class Hamster { constructor(chores) { set(this, 'chores', chores); }
@map('chores', function(chore, index) { return
${chore.toUpperCase()}!
; }) excitingChores; });let hamster = new Hamster(['clean', 'write more unit tests']);
hamster.excitingChores; // ['CLEAN!', 'WRITE MORE UNIT TESTS!'] ```
You can optionally pass an array of additional dependent keys as the second parameter to the macro, if your map function relies on any external values:
```javascript import { set } from '@ember/object'; import { map } from '@ember/object/computed';
class Hamster { shouldUpperCase = false;
constructor(chores) { set(this, 'chores', chores); }
@map('chores', ['shouldUpperCase'], function(chore, index) { if (this.shouldUpperCase) { return
${chore.toUpperCase()}!
; } else { return${chore}!
; } }) excitingChores; }let hamster = new Hamster(['clean', 'write more unit tests']);
hamster.excitingChores; // ['clean!', 'write more unit tests!']
set(hamster, 'shouldUpperCase', true); hamster.excitingChores; // ['CLEAN!', 'WRITE MORE UNIT TESTS!'] ```
map @ember/object/computed
Parameter dependentKey
Parameter additionalDependentKeys
optional array of additional dependent keys
Parameter callback
{ComputedProperty} an array mapped via the callback
Modifiers
@public
function mapBy
mapBy: (dependentKey: string, propertyKey: string) => PropertyDecorator;
Returns an array mapped to the specified key.
Example:
```javascript import { set } from '@ember/object'; import { mapBy } from '@ember/object/computed';
class Person { children = [];
@mapBy('children', 'age') childAges; }
let lordByron = new Person();
lordByron.childAges; // []
set(lordByron, 'children', [ { name: 'Augusta Ada Byron', age: 7 } ]); lordByron.childAges; // [7]
set(lordByron, 'children', [ ...lordByron.children, { name: 'Allegra Byron', age: 5 }, { name: 'Elizabeth Medora Leigh', age: 8 } ]); lordByron.childAges; // [7, 5, 8] ```
mapBy @ember/object/computed
Parameter dependentKey
Parameter propertyKey
{ComputedProperty} an array mapped to the specified key
Modifiers
@public
function max
max: (dependentKey: string) => PropertyDecorator;
A computed property that calculates the maximum value in the dependent array. This will return
-Infinity
when the dependent array is empty.Example:
```javascript import { set } from '@ember/object'; import { mapBy, max } from '@ember/object/computed';
class Person { children = [];
@mapBy('children', 'age') childAges; @max('childAges') maxChildAge; }
let lordByron = new Person();
lordByron.maxChildAge; // -Infinity
set(lordByron, 'children', [ { name: 'Augusta Ada Byron', age: 7 } ]); lordByron.maxChildAge; // 7
set(lordByron, 'children', [ ...lordByron.children, { name: 'Allegra Byron', age: 5 }, { name: 'Elizabeth Medora Leigh', age: 8 } ]); lordByron.maxChildAge; // 8 ```
If the types of the arguments are not numbers, they will be converted to numbers and the type of the return value will always be
Number
. For example, the max of a list of Date objects will be the highest timestamp as aNumber
. This behavior is consistent withMath.max
.max @ember/object/computed
Parameter dependentKey
{ComputedProperty} computes the largest value in the dependentKey's array
Modifiers
@public
function min
min: (dependentKey: string) => PropertyDecorator;
A computed property that calculates the minimum value in the dependent array. This will return
Infinity
when the dependent array is empty.Example:
```javascript import { set } from '@ember/object'; import { mapBy, min } from '@ember/object/computed';
class Person { children = [];
@mapBy('children', 'age') childAges; @min('childAges') minChildAge; }
let lordByron = Person.create({ children: [] });
lordByron.minChildAge; // Infinity
set(lordByron, 'children', [ { name: 'Augusta Ada Byron', age: 7 } ]); lordByron.minChildAge; // 7
set(lordByron, 'children', [ ...lordByron.children, { name: 'Allegra Byron', age: 5 }, { name: 'Elizabeth Medora Leigh', age: 8 } ]); lordByron.minChildAge; // 5 ```
If the types of the arguments are not numbers, they will be converted to numbers and the type of the return value will always be
Number
. For example, the min of a list of Date objects will be the lowest timestamp as aNumber
. This behavior is consistent withMath.min
.min @ember/object/computed
Parameter dependentKey
{ComputedProperty} computes the smallest value in the dependentKey's array
Modifiers
@public
function setDiff
setDiff: (setAProperty: string, setBProperty: string) => PropertyDecorator;
A computed property which returns a new array with all the properties from the first dependent array that are not in the second dependent array.
Example:
```javascript import { set } from '@ember/object'; import { setDiff } from '@ember/object/computed';
class Hamster { constructor(likes, fruits) { set(this, 'likes', likes); set(this, 'fruits', fruits); }
@setDiff('likes', 'fruits') wants; }
let hamster = new Hamster( [ 'banana', 'grape', 'kale' ], [ 'grape', 'kale', ] );
hamster.wants; // ['banana'] ```
setDiff @ember/object/computed
Parameter setAProperty
Parameter setBProperty
{ComputedProperty} computes a new array with all the items from the first dependent array that are not in the second dependent array
Modifiers
@public
function sort
sort: { (itemsKey: string, sortDefinition: SortDefinition | string): PropertyDecorator; ( itemsKey: string, additionalDependentKeys: string[], sortDefinition: SortDefinition ): PropertyDecorator;};
A computed property which returns a new array with all the properties from the first dependent array sorted based on a property or sort function. The sort macro can be used in two different ways:
1. By providing a sort callback function 2. By providing an array of keys to sort the array
In the first form, the callback method you provide should have the following signature:
```javascript function sortCallback(itemA, itemB); ```
-
itemA
the first item to compare. -itemB
the second item to compare.This function should return negative number (e.g.
-1
) whenitemA
should come beforeitemB
. It should return positive number (e.g.1
) whenitemA
should come afteritemB
. If theitemA
anditemB
are equal this function should return0
.Therefore, if this function is comparing some numeric values, simple `itemA - itemB
or
itemA.get( 'foo' ) - itemB.get( 'foo' )` can be used instead of series ofif
.Example:
```javascript import { set } from '@ember/object'; import { sort } from '@ember/object/computed';
class ToDoList { constructor(todos) { set(this, 'todos', todos); }
// using a custom sort function @sort('todos', function(a, b){ if (a.priority > b.priority) { return 1; } else if (a.priority < b.priority) { return -1; }
return 0; }) priorityTodos; }
let todoList = new ToDoList([ { name: 'Unit Test', priority: 2 }, { name: 'Documentation', priority: 3 }, { name: 'Release', priority: 1 } ]);
todoList.priorityTodos; // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }] ```
You can also optionally pass an array of additional dependent keys as the second parameter, if your sort function is dependent on additional values that could changes:
```js import EmberObject, { set } from '@ember/object'; import { sort } from '@ember/object/computed';
class ToDoList { sortKey = 'priority';
constructor(todos) { set(this, 'todos', todos); }
// using a custom sort function @sort('todos', ['sortKey'], function(a, b){ if (a[this.sortKey] > b[this.sortKey]) { return 1; } else if (a[this.sortKey] < b[this.sortKey]) { return -1; }
return 0; }) sortedTodos; });
let todoList = new ToDoList([ { name: 'Unit Test', priority: 2 }, { name: 'Documentation', priority: 3 }, { name: 'Release', priority: 1 } ]);
todoList.priorityTodos; // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }] ```
In the second form, you should provide the key of the array of sort values as the second parameter:
```javascript import { set } from '@ember/object'; import { sort } from '@ember/object/computed';
class ToDoList { constructor(todos) { set(this, 'todos', todos); }
// using standard ascending sort todosSorting = ['name']; @sort('todos', 'todosSorting') sortedTodos;
// using descending sort todosSortingDesc = ['name:desc']; @sort('todos', 'todosSortingDesc') sortedTodosDesc; }
let todoList = new ToDoList([ { name: 'Unit Test', priority: 2 }, { name: 'Documentation', priority: 3 }, { name: 'Release', priority: 1 } ]);
todoList.sortedTodos; // [{ name:'Documentation', priority:3 }, { name:'Release', priority:1 }, { name:'Unit Test', priority:2 }] todoList.sortedTodosDesc; // [{ name:'Unit Test', priority:2 }, { name:'Release', priority:1 }, { name:'Documentation', priority:3 }] ```
sort @ember/object/computed
Parameter itemsKey
Parameter sortDefinitionOrDependentKeys
The key of the sort definition (an array of sort properties), the sort function, or an array of additional dependent keys
Parameter sortDefinition
the sort function (when used with additional dependent keys) {ComputedProperty} computes a new sorted array based on the sort property array or callback function
Modifiers
@public
function sum
sum: (dependentKey: string) => PropertyDecorator;
A computed property that returns the sum of the values in the dependent array.
Example:
```javascript import { sum } from '@ember/object/computed';
class Invoice { lineItems = [1.00, 2.50, 9.99];
@sum('lineItems') total; }
let invoice = new Invoice();
invoice.total; // 13.49 ```
sum @ember/object/computed
Parameter dependentKey
{ComputedProperty} computes the sum of all values in the dependentKey's array 1.4.0
Modifiers
@public
function uniq
uniq: ( dependentKey: string, ...additionalDependentKeys: string[]) => PropertyDecorator;
A computed property which returns a new array with all the unique elements from one or more dependent arrays.
Example:
```javascript import { set } from '@ember/object'; import { uniq } from '@ember/object/computed';
class Hamster { constructor(fruits) { set(this, 'fruits', fruits); }
@uniq('fruits') uniqueFruits; }
let hamster = new Hamster([ 'banana', 'grape', 'kale', 'banana' ]);
hamster.uniqueFruits; // ['banana', 'grape', 'kale'] ```
uniq @ember/object/computed
Parameter propertyKey
* {ComputedProperty} computes a new array with all the unique elements from the dependent array
Modifiers
@public
function uniqBy
uniqBy: (dependentKey: string, propertyKey: string) => PropertyDecorator;
A computed property which returns a new array with all the unique elements from an array, with uniqueness determined by specific key.
Example:
```javascript import { set } from '@ember/object'; import { uniqBy } from '@ember/object/computed';
class Hamster { constructor(fruits) { set(this, 'fruits', fruits); }
@uniqBy('fruits', 'id') uniqueFruits; }
let hamster = new Hamster([ { id: 1, 'banana' }, { id: 2, 'grape' }, { id: 3, 'peach' }, { id: 1, 'banana' } ]);
hamster.uniqueFruits; // [ { id: 1, 'banana' }, { id: 2, 'grape' }, { id: 3, 'peach' }] ```
uniqBy @ember/object/computed
Parameter dependentKey
Parameter propertyKey
{ComputedProperty} computes a new array with all the unique elements from the dependent array
Modifiers
@public
namespace @ember/object/mixin
module '@ember/object/mixin' {}
function applyMixin
applyMixin: ( obj: Record<string, any>, mixins: Array<Mixin | Record<string, unknown>>, _hideKeys?: boolean) => Record<string, any>;
function mixin
mixin: (obj: object, ...args: any[]) => object;
mixin
Parameter obj
Parameter mixins
* obj
class Mixin
class Mixin {}
The
Mixin
class allows you to create mixins, whose properties can be added to other classes. For instance,```javascript import Mixin from '@ember/object/mixin';
const EditableMixin = Mixin.create({ edit() { console.log('starting to edit'); this.set('isEditing', true); }, isEditing: false }); ```
```javascript import EmberObject from '@ember/object'; import EditableMixin from '../mixins/editable';
// Mix mixins into classes by passing them as the first arguments to //
.extend.
const Comment = EmberObject.extend(EditableMixin, { post: null });let comment = Comment.create({ post: somePost });
comment.edit(); // outputs 'starting to edit' ```
Note that Mixins are created with
Mixin.create
, notMixin.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 import Mixin from '@ember/object/mixin'; import { A } from '@ember/array';
const FilterableMixin = Mixin.create({ filters: A() }); ```
```javascript import Mixin from '@ember/object/mixin'; import { A } from '@ember/array'; import { computed } from '@ember/object';
// filters will be a separate array for every object implementing the mixin const FilterableMixin = Mixin.create({ filters: computed(function() { return A(); }) }); ```
```javascript import Mixin from '@ember/object/mixin'; import { A } from '@ember/array';
// filters will be created as a separate array during the object's initialization const Filterable = Mixin.create({ filters: null,
init() { this._super(...arguments); this.set("filters", A()); } }); ```
Mixin
Modifiers
@public
property [INIT_FACTORY]
[INIT_FACTORY]?: null;
method create
static create: <M extends typeof Mixin>(...args: any[]) => InstanceType<M>;
create @ember/object/mixin
Parameter arguments
*
Modifiers
@public
namespace @ember/object/observable
module '@ember/object/observable' {}
variable Observable
const Observable: Mixin;
interface Observable
interface Observable {}
## Overview
This mixin provides properties and property observing functionality, core features of the Ember object model.
Properties and observers allow one object to observe changes to a property on another object. This is one of the fundamental ways that models, controllers and views communicate with each other in an Ember application.
Any object that has this mixin applied can be used in observer operations. That includes
EmberObject
and most objects you will interact with as you write your Ember application.Note that you will not generally apply this mixin to classes yourself, but you will use the features provided by this module frequently, so it is important to understand how to use it.
## Using
get()
andset()
Because of Ember's support for bindings and observers, you will always access properties using the get method, and set properties using the set method. This allows the observing objects to be notified and computed properties to be handled properly.
More documentation about
get
andset
are below.## Observing Property Changes
You typically observe property changes simply by using the
observer
function in classes that you write.For example:
```javascript import { observer } from '@ember/object'; import EmberObject from '@ember/object';
EmberObject.extend({ valueObserver: observer('value', function(sender, key, value, rev) { // Executes whenever the "value" property changes // See the addObserver method for more information about the callback arguments }) }); ```
Although this is the most common way to add an observer, this capability is actually built into the
EmberObject
class on top of two methods defined in this mixin:addObserver
andremoveObserver
. You can use these two methods to add and remove observers yourself if you need to do so at runtime.To add an observer for a property, call:
```javascript object.addObserver('propertyKey', targetObject, targetAction) ```
This will call the
targetAction
method on thetargetObject
whenever the value of thepropertyKey
changes.Note that if
propertyKey
is a computed property, the observer will be called when any of the property dependencies are changed, even if the resulting value of the computed property is unchanged. This is necessary because computed properties are not computed untilget
is called.Observable
Modifiers
@public
method addObserver
addObserver: { <Target>( key: keyof this, target: Target, method: ObserverMethod<Target, this> ): this; (key: keyof this, method: ObserverMethod<this, this>): this;};
Adds an observer on a property.
This is the core method used to register an observer for a property.
Once you call this method, any time the key's value is set, your observer will be notified. Note that the observers are triggered any time the value is set, regardless of whether it has actually changed. Your observer should be prepared to handle that.
There are two common invocation patterns for
.addObserver()
:- Passing two arguments: - the name of the property to observe (as a string) - the function to invoke (an actual function) - Passing three arguments: - the name of the property to observe (as a string) - the target object (will be used to look up and invoke a function on) - the name of the function to invoke on the target object (as a string).
```app/components/my-component.js import Component from '@ember/component';
export default Component.extend({ init() { this._super(...arguments);
// the following are equivalent:
// using three arguments this.addObserver('foo', this, 'fooDidChange');
// using two arguments this.addObserver('foo', (...args) => { this.fooDidChange(...args); }); },
fooDidChange() { // your custom logic code } }); ```
### Observer Methods
Observer methods have the following signature:
```app/components/my-component.js import Component from '@ember/component';
export default Component.extend({ init() { this._super(...arguments); this.addObserver('foo', this, 'fooDidChange'); },
fooDidChange(sender, key, value, rev) { // your code } }); ```
The
sender
is the object that changed. Thekey
is the property that changes. Thevalue
property is currently reserved and unused. Therev
is the last property revision of the object when it changed, which you can use to detect if the key value has really changed or not.Usually you will not need the value or revision parameters at the end. In this case, it is common to write observer methods that take only a sender and key value as parameters or, if you aren't interested in any of these values, to write an observer that has no parameters at all.
addObserver
Parameter key
The key to observe
Parameter target
The target object to invoke
Parameter method
The method to invoke
Parameter sync
Whether the observer is sync or not {Observable}
Modifiers
@public
method cacheFor
cacheFor: <K extends keyof this>(key: K) => unknown;
Returns the cached value of a computed property, if it exists. This allows you to inspect the value of a computed property without accidentally invoking it if it is intended to be generated lazily.
cacheFor
Parameter keyName
{Object} The cached value of the computed property, if any
Modifiers
@public
method decrementProperty
decrementProperty: (keyName: keyof this, decrement?: number) => number;
Set the value of a property to the current value minus some amount.
```javascript player.decrementProperty('lives'); orc.decrementProperty('health', 5); ```
decrementProperty
Parameter keyName
The name of the property to decrement
Parameter decrement
The amount to decrement by. Defaults to 1 {Number} The new property value
Modifiers
@public
method get
get: { <K extends keyof this>(key: K): this[K]; (key: string): unknown };
Retrieves the value of a property from the object.
This method is usually similar to using
object[keyName]
orobject.keyName
, however it supports both computed properties and the unknownProperty handler.Because
get
unifies the syntax for accessing all these kinds of properties, it can make many refactorings easier, such as replacing a simple property with a computed property, or vice versa.### Computed Properties
Computed properties are methods defined with the
property
modifier declared at the end, such as:```javascript import { computed } from '@ember/object';
fullName: computed('firstName', 'lastName', function() { return this.get('firstName') + ' ' + this.get('lastName'); }) ```
When you call
get
on a computed property, the function will be called and the return value will be returned instead of the function itself.### Unknown Properties
Likewise, if you try to call
get
on a property whose value isundefined
, theunknownProperty()
method will be called on the object. If this method returns any value other thanundefined
, it will be returned instead. This allows you to implement "virtual" properties that are not defined upfront.get
Parameter keyName
The property to retrieve {Object} The property value or undefined.
Modifiers
@public
method getProperties
getProperties: { <L extends (keyof this)[]>(list: L): { [Key in L[number]]: this[Key] }; <L extends (keyof this)[]>(...list: L): { [Key in L[number]]: this[Key] }; <L extends string[]>(list: L): { [Key in L[number]]: unknown }; <L extends string[]>(...list: L): { [Key in L[number]]: unknown };};
To get the values of multiple properties at once, call
getProperties
with a list of strings or an array:```javascript record.getProperties('firstName', 'lastName', 'zipCode'); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ```
is equivalent to:
```javascript record.getProperties(['firstName', 'lastName', 'zipCode']); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ```
getProperties
Parameter list
of keys to get {Object}
Modifiers
@public
method incrementProperty
incrementProperty: (keyName: keyof this, increment?: number) => number;
Set the value of a property to the current value plus some amount.
```javascript person.incrementProperty('age'); team.incrementProperty('score', 2); ```
incrementProperty
Parameter keyName
The name of the property to increment
Parameter increment
The amount to increment by. Defaults to 1 {Number} The new property value
Modifiers
@public
method notifyPropertyChange
notifyPropertyChange: (keyName: string) => this;
Convenience method to call
propertyWillChange
andpropertyDidChange
in succession.Notify the observer system that a property has just changed.
Sometimes you need to change a value directly or indirectly without actually calling
get()
orset()
on it. In this case, you can use this method instead. Calling this method will notify all observers that the property has potentially changed value.notifyPropertyChange
Parameter keyName
The property key to be notified about. {Observable}
Modifiers
@public
method removeObserver
removeObserver: { <Target>( key: keyof this, target: Target, method: ObserverMethod<Target, this> ): this; (key: keyof this, method: ObserverMethod<this, this>): this;};
Remove an observer you have previously registered on this object. Pass the same key, target, and method you passed to
addObserver()
and your target will no longer receive notifications.removeObserver
Parameter key
The key to observe
Parameter target
The target object to invoke
Parameter method
The method to invoke
Parameter sync
Whether the observer is async or not {Observable}
Modifiers
@public
method set
set: { <K extends keyof this, T extends this[K]>(key: K, value: T): T; <T>(key: string, value: T): T;};
Sets the provided key or path to the value.
```javascript record.set("key", value); ```
This method is generally very similar to calling
object["key"] = value
orobject.key = value
, except that it provides support for computed properties, thesetUnknownProperty()
method and property observers.### Computed Properties
If you try to set a value on a key that has a computed property handler defined (see the
get()
method for an example), thenset()
will call that method, passing both the value and key instead of simply changing the value itself. This is useful for those times when you need to implement a property that is composed of one or more member properties.### Unknown Properties
If you try to set a value on a key that is undefined in the target object, then the
setUnknownProperty()
handler will be called instead. This gives you an opportunity to implement complex "virtual" properties that are not predefined on the object. IfsetUnknownProperty()
returns undefined, thenset()
will simply set the value on the object.### Property Observers
In addition to changing the property,
set()
will also register a property change with the object. Unless you have placed this call inside of abeginPropertyChanges()
andendPropertyChanges(),
any "local" observers (i.e. observer methods declared on the same object), will be called immediately. Any "remote" observers (i.e. observer methods declared on another object) will be placed in a queue and called at a later time in a coalesced manner.set
Parameter keyName
The property to set
Parameter value
The value to set or
null
. {Object} The passed valueModifiers
@public
method setProperties
setProperties: { <K extends keyof this, P extends { [Key in K]: this[Key] }>(hash: P): P; <T extends Record<string, unknown>>(hash: T): T;};
Sets a list of properties at once. These properties are set inside a single
beginPropertyChanges
andendPropertyChanges
batch, so observers will be buffered.```javascript record.setProperties({ firstName: 'Charles', lastName: 'Jolley' }); ```
setProperties
Parameter hash
the hash of keys and values to set {Object} The passed in hash
Modifiers
@public
method toggleProperty
toggleProperty: (keyName: keyof this) => boolean;
Set the value of a boolean property to the opposite of its current value.
```javascript starship.toggleProperty('warpDriveEngaged'); ```
toggleProperty
Parameter keyName
The name of the property to toggle {Boolean} The new property value
Modifiers
@public
type ObserverMethod
type ObserverMethod<Target, Sender> = | keyof Target | ((this: Target, sender: Sender, key: string, value: any, rev: number) => void);
namespace @ember/object/observers
module '@ember/object/observers' {}
function addObserver
addObserver: ( obj: any, path: string, target: object | Function | null, method?: string | Function, sync?: boolean) => void;
addObserver @ember/object/observers
Parameter obj
Parameter path
Parameter target
Parameter method
Modifiers
@public
function removeObserver
removeObserver: ( obj: any, path: string, target: object | Function | null, method?: string | Function, sync?: boolean) => void;
removeObserver @ember/object/observers
Parameter obj
Parameter path
Parameter target
Parameter method
Modifiers
@public
namespace @ember/object/promise-proxy-mixin
module '@ember/object/promise-proxy-mixin' {}
variable PromiseProxyMixin
const PromiseProxyMixin: Mixin;
interface PromiseProxyMixin
interface PromiseProxyMixin<T> {}
A low level mixin making ObjectProxy promise-aware.
```javascript import { resolve } from 'rsvp'; import $ from 'jquery'; import ObjectProxy from '@ember/object/proxy'; import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
let ObjectPromiseProxy = ObjectProxy.extend(PromiseProxyMixin);
let proxy = ObjectPromiseProxy.create({ promise: resolve($.getJSON('/some/remote/data.json')) });
proxy.then(function(json){ // the json }, function(reason) { // the reason why you have no json }); ```
the proxy has bindable attributes which track the promises life cycle
```javascript proxy.get('isPending') //=> true proxy.get('isSettled') //=> false proxy.get('isRejected') //=> false proxy.get('isFulfilled') //=> false ```
When the $.getJSON completes, and the promise is fulfilled with json, the life cycle attributes will update accordingly. Note that $.getJSON doesn't return an ECMA specified promise, it is useful to wrap this with an
RSVP.resolve
so that it behaves as a spec compliant promise.```javascript proxy.get('isPending') //=> false proxy.get('isSettled') //=> true proxy.get('isRejected') //=> false proxy.get('isFulfilled') //=> true ```
As the proxy is an ObjectProxy, and the json now its content, all the json properties will be available directly from the proxy.
```javascript // Assuming the following json: { firstName: 'Stefan', lastName: 'Penner' }
// both properties will accessible on the proxy proxy.get('firstName') //=> 'Stefan' proxy.get('lastName') //=> 'Penner' ```
PromiseProxyMixin
Modifiers
@public
property catch
catch: this['promise']['catch'];
An alias to the proxied promise's
catch
.See RSVP.Promise.catch.
catch
Parameter callback
{RSVP.Promise} 1.3.0
Modifiers
@public
property finally
finally: this['promise']['finally'];
An alias to the proxied promise's
finally
.See RSVP.Promise.finally.
finally
Parameter callback
{RSVP.Promise} 1.3.0
Modifiers
@public
property isFulfilled
isFulfilled: boolean;
Will become
true
if the proxied promise is fulfilled.isFulfilled false
Modifiers
@public
property isPending
readonly isPending: boolean;
Once the proxied promise has settled this will become
false
.isPending true
Modifiers
@public
property isRejected
isRejected: boolean;
Will become
true
if the proxied promise is rejected.isRejected false
Modifiers
@public
property isSettled
readonly isSettled: boolean;
Once the proxied promise has settled this will become
true
.isSettled false
Modifiers
@public
property promise
promise: Promise<T>;
The promise whose fulfillment value is being proxied by this object.
This property must be specified upon creation, and should not be changed once created.
Example:
```javascript import ObjectProxy from '@ember/object/proxy'; import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
ObjectProxy.extend(PromiseProxyMixin).create({ promise: }); ```
promise
Modifiers
@public
property reason
reason: unknown;
If the proxied promise is rejected this will contain the reason provided.
reason null
Modifiers
@public
property then
then: this['promise']['then'];
An alias to the proxied promise's
then
.See RSVP.Promise.then.
then
Parameter callback
{RSVP.Promise}
Modifiers
@public
namespace @ember/object/proxy
module '@ember/object/proxy' {}
class ObjectProxy
class ObjectProxy<Content = unknown> extends FrameworkObject {}
interface ObjectProxy
interface ObjectProxy<Content = unknown> extends _ProxyMixin<Content> {}
ObjectProxy
forwards all properties not defined by the proxy itself to a proxiedcontent
object.```javascript import EmberObject from '@ember/object'; import ObjectProxy from '@ember/object/proxy';
let exampleObject = EmberObject.create({ name: 'Foo' });
let exampleProxy = ObjectProxy.create({ content: exampleObject });
// Access and change existing properties exampleProxy.get('name'); // 'Foo' exampleProxy.set('name', 'Bar'); exampleObject.get('name'); // 'Bar'
// Create new 'description' property on
exampleObject
exampleProxy.set('description', 'Foo is a whizboo baz'); exampleObject.get('description'); // 'Foo is a whizboo baz' ```While
content
is unset, setting a property to be delegated will throw an Error.```javascript import ObjectProxy from '@ember/object/proxy';
let exampleProxy = ObjectProxy.create({ content: null, flag: null }); exampleProxy.set('flag', true); exampleProxy.get('flag'); // true exampleProxy.get('foo'); // undefined exampleProxy.set('foo', 'data'); // throws Error ```
Delegated properties can be bound to and will change when content is updated.
Computed properties on the proxy itself can depend on delegated properties.
```javascript import { computed } from '@ember/object'; import ObjectProxy from '@ember/object/proxy';
ProxyWithComputedProperty = ObjectProxy.extend({ fullName: computed('firstName', 'lastName', function() { var firstName = this.get('firstName'), lastName = this.get('lastName'); if (firstName && lastName) { return firstName + ' ' + lastName; } return firstName || lastName; }) });
let exampleProxy = ProxyWithComputedProperty.create();
exampleProxy.get('fullName'); // undefined exampleProxy.set('content', { firstName: 'Tom', lastName: 'Dale' }); // triggers property change for fullName on proxy
exampleProxy.get('fullName'); // 'Tom Dale' ```
ObjectProxy EmberObject Ember.ProxyMixin
Modifiers
@public
method get
get: { <K extends keyof Content>(keyName: K): Content[K]; <K extends keyof this>(keyname: K): this[K]; (keyName: string): unknown;};
method getProperties
getProperties: { <K extends keyof Content | keyof this>(list: K[]): Pick< Content, Exclude<K, keyof this> > & Pick<this, Exclude<K, keyof Content>>; <K extends keyof Content | keyof this>(...list: K[]): Pick< Content, Exclude<K, keyof this> > & Pick<this, Exclude<K, keyof Content>>; <K extends string>(list: K[]): Record<K, unknown>; <K extends string>(...list: K[]): Record<K, unknown>;};
method set
set: { <K extends keyof Content>(keyName: K, value: Content[K]): Content[K]; <K extends keyof this>(keyName: K, value: this[K]): this[K]; (keyName: string): unknown;};
method setProperties
setProperties: { < K extends keyof Content | keyof this, Hash extends Partial< Pick<Content, Exclude<K, keyof this>> & Pick<this, Exclude<K, keyof Content>> > >( hash: Hash ): Hash; <T extends Record<string, unknown>>(hash: T): T;};
namespace @ember/owner
module '@ember/owner' {}
function getOwner
getOwner: (object: object) => Owner | undefined;
Framework objects in an Ember application (components, services, routes, etc.) are created via a factory and dependency injection system. Each of these objects is the responsibility of an "owner", which handled its instantiation and manages its lifetime.
getOwner
fetches the owner object responsible for an instance. This can be used to lookup or resolve other class instances, or register new factories into the owner.For example, this component dynamically looks up a service based on the
audioType
passed as an argument:```app/components/play-audio.js import Component from '@glimmer/component'; import { action } from '@ember/object'; import { getOwner } from '@ember/owner';
// Usage: // // <PlayAudio @audioType={{@model.audioType}} @audioFile={{@model.file}}/> // export default class extends Component { get audioService() { return getOwner(this)?.lookup(
service:${this.args.audioType}
); }onPlay() { this.audioService?.play(this.args.audioFile); } } ```
getOwner @ember/owner
Parameter object
An object with an owner. {Object} An owner object. 2.3.0
Modifiers
@public
function setOwner
setOwner: (object: object, owner: Owner) => void;
setOwner
forces a new owner on a given object instance. This is primarily useful in some testing cases.setOwner @ember/owner
Parameter object
An object instance.
Parameter object
The new owner object of the object instance. 2.3.0
Modifiers
@public
interface DIRegistry
interface DIRegistry {}
A type registry for the DI system, which other participants in the DI system can register themselves into with declaration merging. The contract for this type is that its keys are the
Type
from aFullName
, and each value for aType
is another registry whose keys are theName
from aFullName
. The mechanic for providing a registry is [declaration merging][handbook].[handbook]: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
For example, Ember's
@ember/service
module includes this set of definitions:```ts export default class Service extends EmberObject {}
// For concrete singleton classes to be merged into. interface Registry extends Record<string, Service> {}
declare module '@ember/owner' { service: Registry; } ```
Declarations of services can then include the registry:
```ts import Service from '@ember/service';
export default class Session extends Service { login(username: string, password: string) { // ... } }
declare module '@ember/service' { interface Registry { session: Session; } } ```
Then users of the
Owner
API will be able to do things like this with strong type safety guarantees:```ts getOwner(this)?.lookup('service:session').login("hello", "1234abcd"); ```
@ember/owner
interface Factory
interface Factory<T extends object> {}
Registered factories are instantiated by having create called on them. Additionally they are singletons by default, so each time they are looked up they return the same instance.
However, that behavior can be modified with the
instantiate
andsingleton
options to theOwner.register()
method.@ember/owner Factory 4.10.0
Modifiers
@public
method create
create: (initialValues?: object) => T;
A function that will create an instance of the class with any dependencies injected.
create
Parameter initialValues
Any values to set on an instance of the class {Object} The item produced by the factory.
Modifiers
@public
interface FactoryManager
interface FactoryManager<T extends object> extends Factory<T> {}
The interface representing a manager which can be used for introspection of the factory's class or for the creation of factory instances with initial properties. The manager is an object with the following properties:
-
class
- The registered or resolved class. -create
- A function that will create an instance of the class with any dependencies injected.*Note:**
FactoryManager
is *not* user-constructible; the only legal way to get aFactoryManager
is viaOwner.factoryFor
.@ember/owner FactoryManager Factory
Modifiers
@public
property class
readonly class: Factory<T>;
The registered or resolved class.
class Factory
Modifiers
@public
interface Owner
interface Owner extends BasicRegistry, BasicContainer {}
Framework objects in an Ember application (components, services, routes, etc.) are created via a factory and dependency injection system. Each of these objects is the responsibility of an "owner", which handles its instantiation and manages its lifetime.
An
Owner
is not a class you construct; it is one the framework constructs for you. The normal way to get access to the relevantOwner
is using thegetOwner
function.@ember/owner BasicRegistry BasicContainer Owner 4.10.0
Modifiers
@public
interface RegisterOptions
interface RegisterOptions {}
Interface representing the options for registering an item as a factory.
@ember/owner RegisterOptions
Modifiers
@public
property instantiate
instantiate?: boolean | undefined;
Whether to instantiate the item when returning it from a lookup. Defaults to
true
.instantiate Boolean true
Modifiers
@public
property singleton
singleton?: boolean | undefined;
Whether the item is a singleton (like a service) and so should return the same instance every time, or should generate a new instance on each call. Defaults to
true
.singleton Boolean true
Modifiers
@public
interface Resolver
interface Resolver {}
A
Resolver
is the mechanism responsible for looking up code in your application and converting its naming conventions into the actual classes, functions, and templates that Ember needs to resolve its dependencies, for example, what template to render for a given route. It is a system that helps the app resolve the lookup of JavaScript modules agnostic of what kind of module system is used, which can be AMD, CommonJS or just plain globals. It is used to lookup routes, models, components, templates, or anything that is used in your Ember app.This interface is not a concrete class; instead, it represents the contract a custom resolver must implement. Most apps never need to think about this: in the default blueprint, this is supplied by the
ember-resolver
package.@ember/owner Resolver 4.10.0
Modifiers
@public
property knownForType
knownForType?: <Type extends string>(type: Type) => KnownForTypeResult<Type>;
knownForType
Parameter type
{Object}
Modifiers
@public
property lookupDescription
lookupDescription?: (fullName: FullName) => string;
lookupDescription
Parameter fullName
{String}
Modifiers
@public
property makeToString
makeToString?: (factory: Factory<object>, fullName: FullName) => string;
makeToString
Parameter factory
Parameter fullName
{String}
Modifiers
@public
property normalize
normalize?: (fullName: FullName) => FullName;
normalize
Parameter fullName
{String}
Modifiers
@public
property resolve
resolve: (name: string) => Factory<object> | object | undefined;
The one required method for a
Resolver
. Given a string, resolve it to aFactory
, if one exists.resolve
Parameter name
Modifiers
@public
type FullName
type FullName< Type extends string = string, Name extends string = string> = `${Type}:${Name}`;
The name for a factory consists of a namespace and the name of a specific type within that namespace, like
'service:session'
.*Note:**
FullName
is *not* a class, just a contract for strings used in the DI system. It is currently documented as a class only due to limits in our documentation infrastructure.@ember/owner FullName
Modifiers
@public
type KnownForTypeResult
type KnownForTypeResult<Type extends string> = { [Key in FullName<Type, string>]: boolean | undefined;};
A record mapping all known items of a given type: if the item is known it will be
true
; otherwise it will befalse
orundefined
.
namespace @ember/renderer
module '@ember/renderer' {}
function renderSettled
renderSettled: () => RSVP.Promise<void>;
namespace @ember/routing
module '@ember/routing' {}
namespace @ember/routing/-internals
module '@ember/routing/-internals' {}
function controllerFor
controllerFor: ( container: Container, controllerName: string, lookupOptions: RegisterOptions) => InternalFactory<object, FactoryClass> | object | undefined;
Finds a controller instance.
Ember controllerFor
function generateController
generateController: (owner: Owner, controllerName: string) => Controller;
Generates and instantiates a controller extending from
controller:basic
if present, orController
if not.Ember generateController 1.3.0
function generateControllerFactory
generateControllerFactory: ( owner: Owner, controllerName: string) => InternalFactory<{}>;
Generates a controller factory
Ember generateControllerFactory
function prefixRouteNameArg
prefixRouteNameArg: <T extends NamedRouteArgs | UnnamedRouteArgs>( route: Route, args: T) => T;
class BucketCache
class BucketCache {}
A two-tiered cache with support for fallback values when doing lookups. Uses "buckets" and then "keys" to cache values.
BucketCache
constructor
constructor();
property cache
cache: Map<string, Map<string, any>>;
method has
has: (bucketKey: string) => boolean;
method lookup
lookup: (bucketKey: string, prop: string, defaultValue: any) => any;
method stash
stash: (bucketKey: string, key: string, value: any) => void;
class DSL
class DSLImpl implements DSL {}
constructor
constructor(name: string, options: DSLImplOptions);
property enableLoadingSubstates
enableLoadingSubstates: boolean;
property explicitIndex
explicitIndex: boolean;
property matches
matches: Object[];
property options
options: DSLImplOptions;
property parent
parent: string;
method generate
generate: () => MatchCallback;
method mount
mount: (_name: string, options?: MountOptions) => void;
method push
push: ( url: string, name: string, callback?: MatchCallback, serialize?: (model: {}, params: string[]) => { [key: string]: unknown }) => void;
method route
route: { (name: string): void; (name: string, callback: DSLCallback): void; (name: string, options: RouteOptions): void; (name: string, options: RouteOptions, callback: DSLCallback): void;};
class RouterState
class RouterState {}
constructor
constructor( emberRouter: EmberRouter, router: Router<Route<unknown>>, routerJsState: TransitionState<Route<unknown>>);
property emberRouter
emberRouter: EmberRouter;
property router
router: Router<Route<unknown>>;
property routerJsState
routerJsState: TransitionState<Route<unknown>>;
method isActiveIntent
isActiveIntent: ( routeName: string, models: ModelFor<Route>[], queryParams?: Record<string, unknown>) => boolean;
class RoutingService
class RoutingService<R extends Route> extends Service {}
The Routing service is used by LinkTo, and provides facilities for the component/view layer to interact with the router.
This is a private service for internal usage only. For public usage, refer to the
Router
service.RoutingService
property [ROUTER]
[ROUTER]?: EmberRouter;
property currentPath
currentPath: string;
property currentRouteName
currentRouteName: string;
property currentState
currentState: RouterState;
property router
readonly router: EmberRouter;
property targetState
targetState: RouterState;
method generateURL
generateURL: ( routeName: string, models: ModelFor<R>[], queryParams: Record<string, unknown>) => string | undefined;
method hasRoute
hasRoute: (routeName: string) => boolean;
method isActiveForRoute
isActiveForRoute: ( contexts: ModelFor<R>[], queryParams: Record<string, unknown> | undefined, routeName: string, routerState: RouterState) => boolean;
method normalizeQueryParams
normalizeQueryParams: ( routeName: string, models: ModelFor<R>[], queryParams: Record<string, unknown>) => void;
method transitionTo
transitionTo: ( routeName: string, models: ModelFor<R>[], queryParams: Record<string, unknown>, shouldReplace: boolean) => any;
interface DSLCallback
interface DSLCallback {}
call signature
(this: DSL): void;
interface EngineRouteInfo
interface EngineRouteInfo extends EngineInfo {}
property localFullName
localFullName: string;
property serializeMethod
serializeMethod?: ( model: {}, params: string[]) => { [key: string]: unknown | undefined;};
type RouteArgs
type RouteArgs = NamedRouteArgs | UnnamedRouteArgs;
namespace @ember/routing/hash-location
module '@ember/routing/hash-location' {}
class HashLocation
class HashLocation extends EmberObject implements EmberLocation {}
HashLocation
implements the location API using the browser's hash. At present, it relies on ahashchange
event existing in the browser.Using
HashLocation
results in URLs with a#
(hash sign) separating the server side URL portion of the URL from the portion that is used by Ember.Example:
```app/router.js Router.map(function() { this.route('posts', function() { this.route('new'); }); });
Router.reopen({ location: 'hash' }); ```
This will result in a posts.new url of
/#/posts/new
.HashLocation EmberObject
property lastSetURL
lastSetURL: string;
property location
location: Location;
method formatURL
formatURL: (url: string) => string;
Given a URL, formats it to be placed into the page as part of an element's
href
attribute.formatURL
Parameter url
method getHash
getHash: () => string;
Returns normalized location.hash
1.5.1 getHash
method getURL
getURL: () => string;
Returns the normalized URL, constructed from
location.hash
.e.g.
#/foo
=>/foo
as well as#/foo#bar
=>/foo#bar
.By convention, hashed paths must begin with a forward slash, otherwise they are not treated as a path so we can distinguish intent.
getURL
method init
init: () => void;
method onUpdateURL
onUpdateURL: (callback: UpdateCallback) => void;
Register a callback to be invoked when the hash changes. These callbacks will execute when the user presses the back or forward button, but not after
setURL
is invoked.onUpdateURL
Parameter callback
method replaceURL
replaceURL: (path: string) => void;
Uses location.replace to update the url without a page reload or history modification.
replaceURL
Parameter path
method setURL
setURL: (path: string) => void;
Set the
location.hash
and remembers what was set. This preventsonUpdateURL
callbacks from triggering when the hash was set byHashLocation
.setURL
Parameter path
method willDestroy
willDestroy: () => void;
Cleans up the HashLocation event listener.
willDestroy
namespace @ember/routing/history-location
module '@ember/routing/history-location' {}
class HistoryLocation
class HistoryLocation extends EmberObject implements EmberLocation {}
HistoryLocation implements the location API using the browser's history.pushState API.
Using
HistoryLocation
results in URLs that are indistinguishable from a standard URL. This relies upon the browser'shistory
API.Example:
```app/router.js Router.map(function() { this.route('posts', function() { this.route('new'); }); });
Router.reopen({ location: 'history' }); ```
This will result in a posts.new url of
/posts/new
.Keep in mind that your server must serve the Ember app at all the routes you define.
Using
HistoryLocation
will also result in location states being recorded by the browserhistory
API with the following schema:``` window.history.state -> { path: '/', uuid: '3552e730-b4a6-46bd-b8bf-d8c3c1a97e0a' } ```
This allows each in-app location state to be tracked uniquely across history state changes via the
uuid
field.HistoryLocation EmberObject
property baseURL
baseURL: string;
property history
history?: History;
property location
location: Location;
property rootURL
rootURL: string;
Will be pre-pended to path upon state change
rootURL '/'
method formatURL
formatURL: (url: string) => string;
Formats url to be placed into href attribute.
formatURL
Parameter url
formatted url {String}
method getHash
getHash: () => string;
Returns normalized location.hash
getHash
method getURL
getURL: () => string;
Returns the current
location.pathname
withoutrootURL
orbaseURL
getURL url {String}
method init
init: () => void;
method initState
initState: () => void;
Used to set state on first call to setURL
initState
method onUpdateURL
onUpdateURL: (callback: UpdateCallback) => void;
Register a callback to be invoked whenever the browser history changes, including using forward and back buttons.
onUpdateURL
Parameter callback
method pushState
pushState: (path: string) => void;
Pushes a new state.
pushState
Parameter path
method replaceState
replaceState: (path: string) => void;
Replaces the current state.
replaceState
Parameter path
method replaceURL
replaceURL: (path: string) => void;
Uses
history.replaceState
to update the url without a page reload or history modification.replaceURL
Parameter path
method setURL
setURL: (path: string) => void;
Uses
history.pushState
to update the url without a page reload.setURL
Parameter path
method willDestroy
willDestroy: () => void;
Cleans up the HistoryLocation event listener.
willDestroy
namespace @ember/routing/lib/cache
module '@ember/routing/lib/cache' {}
class BucketCache
class BucketCache {}
A two-tiered cache with support for fallback values when doing lookups. Uses "buckets" and then "keys" to cache values.
BucketCache
constructor
constructor();
property cache
cache: Map<string, Map<string, any>>;
method has
has: (bucketKey: string) => boolean;
method lookup
lookup: (bucketKey: string, prop: string, defaultValue: any) => any;
method stash
stash: (bucketKey: string, key: string, value: any) => void;
namespace @ember/routing/lib/controller_for
module '@ember/routing/lib/controller_for' {}
function controllerFor
controllerFor: ( container: Container, controllerName: string, lookupOptions: RegisterOptions) => InternalFactory<object, FactoryClass> | object | undefined;
Finds a controller instance.
Ember controllerFor
namespace @ember/routing/lib/dsl
module '@ember/routing/lib/dsl' {}
class DSLImpl
class DSLImpl implements DSL {}
constructor
constructor(name: string, options: DSLImplOptions);
property enableLoadingSubstates
enableLoadingSubstates: boolean;
property explicitIndex
explicitIndex: boolean;
property matches
matches: Object[];
property options
options: DSLImplOptions;
property parent
parent: string;
method generate
generate: () => MatchCallback;
method mount
mount: (_name: string, options?: MountOptions) => void;
method push
push: ( url: string, name: string, callback?: MatchCallback, serialize?: (model: {}, params: string[]) => { [key: string]: unknown }) => void;
method route
route: { (name: string): void; (name: string, callback: DSLCallback): void; (name: string, options: RouteOptions): void; (name: string, options: RouteOptions, callback: DSLCallback): void;};
interface DSL
interface DSL {}
interface DSLCallback
interface DSLCallback {}
call signature
(this: DSL): void;
interface DSLImplOptions
interface DSLImplOptions {}
property enableLoadingSubstates
enableLoadingSubstates: boolean;
property engineInfo
engineInfo?: EngineInfo;
method addRouteForEngine
addRouteForEngine: (name: string, routeOptions: EngineRouteInfo) => void;
method resolveRouteMap
resolveRouteMap: (name: string) => InternalFactory<any, any>;
interface MountOptions
interface MountOptions {}
interface RouteOptions
interface RouteOptions {}
property overrideNameAssertion
overrideNameAssertion?: boolean;
property path
path?: string;
property resetNamespace
resetNamespace?: boolean;
property serialize
serialize?: ( model: {}, params: string[]) => { [key: string]: unknown | undefined;};
namespace @ember/routing/lib/engines
module '@ember/routing/lib/engines' {}
interface EngineInfo
interface EngineInfo {}
property fullName
fullName: string;
property instanceId
instanceId: number;
property mountPoint
mountPoint: string;
property name
name: string;
interface EngineRouteInfo
interface EngineRouteInfo extends EngineInfo {}
property localFullName
localFullName: string;
property serializeMethod
serializeMethod?: ( model: {}, params: string[]) => { [key: string]: unknown | undefined;};
namespace @ember/routing/lib/generate_controller
module '@ember/routing/lib/generate_controller' {}
function generateController
generateController: (owner: Owner, controllerName: string) => Controller;
Generates and instantiates a controller extending from
controller:basic
if present, orController
if not.Ember generateController 1.3.0
function generateControllerFactory
generateControllerFactory: ( owner: Owner, controllerName: string) => InternalFactory<{}>;
Generates a controller factory
Ember generateControllerFactory
namespace @ember/routing/lib/location-utils
module '@ember/routing/lib/location-utils' {}
function getFullPath
getFullPath: (location: Location) => string;
function getHash
getHash: (location: Location) => string;
Returns the hash or empty string
function getOrigin
getOrigin: (location: Location) => string;
function getPath
getPath: (location: Location) => string;
Returns the current
location.pathname
, normalized for IE inconsistencies.
function getQuery
getQuery: (location: Location) => string;
Returns the current
location.search
.
function replacePath
replacePath: (location: Location, path: string) => void;
Replaces the current location, making sure we explicitly include the origin to prevent redirecting to a different origin.
namespace @ember/routing/lib/query_params
module '@ember/routing/lib/query_params' {}
class QueryParams
class QueryParams {}
constructor
constructor(values?: null);
property isQueryParams
isQueryParams: boolean;
property values
values: {};
namespace @ember/routing/lib/route-info
module '@ember/routing/lib/route-info' {}
namespace @ember/routing/lib/router_state
module '@ember/routing/lib/router_state' {}
class RouterState
class RouterState {}
constructor
constructor( emberRouter: EmberRouter, router: Router<Route<unknown>>, routerJsState: TransitionState<Route<unknown>>);
property emberRouter
emberRouter: EmberRouter;
property router
router: Router<Route<unknown>>;
property routerJsState
routerJsState: TransitionState<Route<unknown>>;
method isActiveIntent
isActiveIntent: ( routeName: string, models: ModelFor<Route>[], queryParams?: Record<string, unknown>) => boolean;
namespace @ember/routing/lib/routing-service
module '@ember/routing/lib/routing-service' {}
class RoutingService
class RoutingService<R extends Route> extends Service {}
The Routing service is used by LinkTo, and provides facilities for the component/view layer to interact with the router.
This is a private service for internal usage only. For public usage, refer to the
Router
service.RoutingService
property [ROUTER]
[ROUTER]?: EmberRouter;
property currentPath
currentPath: string;
property currentRouteName
currentRouteName: string;
property currentState
currentState: RouterState;
property router
readonly router: EmberRouter;
property targetState
targetState: RouterState;
method generateURL
generateURL: ( routeName: string, models: ModelFor<R>[], queryParams: Record<string, unknown>) => string | undefined;
method hasRoute
hasRoute: (routeName: string) => boolean;
method isActiveForRoute
isActiveForRoute: ( contexts: ModelFor<R>[], queryParams: Record<string, unknown> | undefined, routeName: string, routerState: RouterState) => boolean;
method normalizeQueryParams
normalizeQueryParams: ( routeName: string, models: ModelFor<R>[], queryParams: Record<string, unknown>) => void;
method transitionTo
transitionTo: ( routeName: string, models: ModelFor<R>[], queryParams: Record<string, unknown>, shouldReplace: boolean) => any;
namespace @ember/routing/lib/utils
module '@ember/routing/lib/utils' {}
function calculateCacheKey
calculateCacheKey: ( prefix: string, parts: string[] | undefined, values: {} | null) => string;
function extractRouteArgs
extractRouteArgs: (args: RouteArgs) => ExtractedArgs;
function getActiveTargetName
getActiveTargetName: (router: Router<Route<unknown>>) => string;
function normalizeControllerQueryParams
normalizeControllerQueryParams: ( queryParams: Readonly<ControllerQueryParam[]>) => Record<string, ExpandedControllerQueryParam>;
function prefixRouteNameArg
prefixRouteNameArg: <T extends NamedRouteArgs | UnnamedRouteArgs>( route: Route, args: T) => T;
function resemblesURL
resemblesURL: (str: unknown) => str is string;
function shallowEqual
shallowEqual: <A extends object, B extends object>(a: A, b: B) => boolean;
function stashParamNames
stashParamNames: ( router: EmberRouter, routeInfos: Array<ExtendedInternalRouteInfo<Route>> & { _namesStashed?: boolean }) => void;
type ExpandedControllerQueryParam
type ExpandedControllerQueryParam = { as: string | null; scope: string; type?: ControllerQueryParamType;};
type NamedRouteArgs
type NamedRouteArgs = | [routeNameOrUrl: string, ...modelsAndOptions: [...unknown[], RouteOptions]] | [routeNameOrUrl: string, ...models: unknown[]];
type RouteArgs
type RouteArgs = NamedRouteArgs | UnnamedRouteArgs;
type RouteOptions
type RouteOptions = { queryParams: Record<string, unknown>;};
type UnnamedRouteArgs
type UnnamedRouteArgs = | [...modelsAndOptions: [...unknown[], RouteOptions]] | [...models: unknown[]] | [options: RouteOptions];
namespace @ember/routing/location
module '@ember/routing/location' {}
interface Location
interface Location {}
Location
defines an interface to be implemented bylocation
APIs. It is not user-constructible; the only valid way to get aLocation
is via one of its concrete implementations.## Implementations
You can pass an implementation name (
hash
,history
,none
) to force a particular implementation to be used in your application.- See [HashLocation](/ember/release/classes/HashLocation). - See [HistoryLocation](/ember/release/classes/HistoryLocation). - See [NoneLocation](/ember/release/classes/NoneLocation).
## Location API
Each location implementation must provide the following methods:
getURL
: returns the current URL.setURL(path)
: sets the current URL.replaceURL(path)
: replace the current URL (optional).onUpdateURL(callback)
: triggers the callback when the URL changes.formatURL(url)
: formatsurl
to be placed intohref
attribute.Calling
setURL
orreplaceURL
will not trigger onUpdateURL callbacks.## Custom implementation
Ember scans
app/locations/*
for extending the Location API.Example:
```javascript import HistoryLocation from '@ember/routing/history-location';
export default class MyHistory { implementation = 'my-custom-history';
constructor() { this._history = HistoryLocation.create(...arguments); }
create() { return new this(...arguments); }
pushState(path) { this._history.pushState(path); } } ```
@ember/routing/location Location 5.0.0
Modifiers
@public
property cancelRouterSetup
cancelRouterSetup?: boolean;
If the location needs to redirect to a different URL, it can cancel routing by setting the
cancelRouterSetup
property on itself to false. cancelRouterSetup Boolean trueModifiers
@public
method destroy
destroy: () => void;
method formatURL
formatURL: (url: string) => string;
Formats url to be placed into href attribute.
formatURL
Parameter url
the url to format
Modifiers
@public
method getURL
getURL: () => string;
The current URL. currentURL String
Modifiers
@public
method initState
initState: () => void;
method onUpdateURL
onUpdateURL: (callback: UpdateCallback) => void;
triggers the callback when the URL changes.
Parameter callback
A function to run when the URL changes. The the new URL string is provided as the only argument.
method replaceURL
replaceURL: (url: string) => void;
Replace the current URL (optional). Calling
replaceURL
will not triggeronUpdateURL
callbacks.replaceURL
Parameter url
the new URL to replace the current URL with.
Modifiers
@public
method setURL
setURL: (url: string) => void;
Sets the current URL. Calling
setURL
will not triggeronUpdateURL
callbacks.setURL
Parameter url
the new URL to update to.
Modifiers
@public
interface Registry
interface Registry extends Record<string, Location | undefined> {}
type UpdateCallback
type UpdateCallback = (url: string) => void;
namespace @ember/routing/none-location
module '@ember/routing/none-location' {}
class NoneLocation
class NoneLocation extends EmberObject implements EmberLocation {}
NoneLocation does not interact with the browser. It is useful for testing, or when you need to manage state with your Router, but temporarily don't want it to muck with the URL (for example when you embed your application in a larger page).
Using
NoneLocation
causes Ember to not store the applications URL state in the actual URL. This is generally used for testing purposes, and is one of the changes made when callingApp.setupForTesting()
.NoneLocation EmberObject
property path
path: string;
property rootURL
rootURL: string;
Will be pre-pended to path.
rootURL '/'
property updateCallback
updateCallback?: UpdateCallback;
method formatURL
formatURL: (url: string) => string;
Given a URL, formats it to be placed into the page as part of an element's
href
attribute.formatURL
Parameter url
{String} url
method getURL
getURL: () => string;
Returns the current path without
rootURL
.getURL {String} path
method handleURL
handleURL: (url: string) => void;
Sets the path and calls the
updateURL
callback.handleURL
Parameter url
method initState
initState: () => void;
method onUpdateURL
onUpdateURL: (callback: (url: string) => void) => void;
Register a callback to be invoked when the path changes. These callbacks will execute when the user presses the back or forward button, but not after
setURL
is invoked.onUpdateURL
Parameter callback
method setURL
setURL: (path: string) => void;
Set the path and remembers what was set. Using this method to change the path will not invoke the
updateURL
callback.setURL
Parameter path
namespace @ember/routing/route
module '@ember/routing/route' {}
function defaultSerialize
defaultSerialize: (model: any, params: string[]) => { [key: string]: unknown };
function getFullQueryParams
getFullQueryParams: ( router: EmberRouter, state: RouteTransitionState) => Record<string, unknown>;
function getRenderState
getRenderState: (route: Route) => RenderState | undefined;
function hasDefaultSerialize
hasDefaultSerialize: (route: Route) => boolean;
class Route
class Route<Model = unknown> extends Route_base implements IRoute {}
constructor
constructor(owner?: Owner);
property [RENDER_STATE]
[RENDER_STATE]: RenderState;
property actions
actions: Record<string, AnyFn>;
property controller
controller: Controller<unknown>;
The controller associated with this route.
Example
```app/routes/form.js import Route from '@ember/routing/route'; import { action } from '@ember/object';
export default class FormRoute extends Route { willTransition(transition) { if (this.controller.get('userHasEnteredData') && !confirm('Are you sure you want to abandon progress?')) { transition.abort(); } else { // Bubble the
willTransition
action so that // parent routes can decide whether or not to abort. return true; } } } ```controller Controller 1.6.0
Modifiers
@public
property controllerName
controllerName: string;
The name of the controller to associate with this route.
By default, Ember will lookup a route's controller that matches the name of the route (i.e.
posts.new
). However, if you would like to define a specific controller to use, you can do so using this property.This is useful in many ways, as the controller specified will be:
passed to the
setupController
method. used as the controller for the template being rendered by the route. returned from a call tocontrollerFor
for the route.controllerName String null 1.4.0
Modifiers
@public
property fullRouteName
fullRouteName: string;
The name of the route, dot-delimited, including the engine prefix if applicable.
For example, a route found at
addon/routes/posts/post.js
within an engine namedadmin
will have afullRouteName
ofadmin.posts.post
.fullRouteName Route String 2.10.0
Modifiers
@public
property isRouteFactory
static isRouteFactory: boolean;
property queryParams
queryParams: Record< string, { refreshModel?: boolean; replace?: boolean; as?: string }>;
Configuration hash for this route's queryParams. The possible configuration options and their defaults are as follows (assuming a query param whose controller property is
page
):```javascript queryParams = { page: { // By default, controller query param properties don't // cause a full transition when they are changed, but // rather only cause the URL to update. Setting //
refreshModel
to true will cause an "in-place" // transition to occur, whereby the model hooks for // this route (and any child routes) will re-fire, allowing // you to reload models (e.g., from the server) using the // updated query param values. refreshModel: false,// By default, changes to controller query param properties // cause the URL to update via
pushState
, which means an // item will be added to the browser's history, allowing // you to use the back button to restore the app to the // previous state before the query param property was changed. // Settingreplace
to true will usereplaceState
(or its // hash location equivalent), which causes no browser history // item to be added. This options name and default value are // the same as thelink-to
helper'sreplace
option. replace: false,// By default, the query param URL key is the same name as // the controller property name. Use
as
to specify a // different URL key. as: 'page' } }; ```queryParams Route Object 1.6.0
Modifiers
@public
property routeName
routeName: string;
The name of the route, dot-delimited.
For example, a route found at
app/routes/posts/post.js
will have arouteName
ofposts.post
.routeName Route String 1.0.0
Modifiers
@public
property send
send: <K extends keyof this | keyof this['actions']>( name: K, ...args: MaybeParameters< K extends keyof this ? this[K] : K extends keyof this['actions'] ? this['actions'][K] : never >) => MaybeReturnType< K extends keyof this ? this[K] : K extends keyof this['actions'] ? this['actions'][K] : never>;
Sends an action to the router, which will delegate it to the currently active route hierarchy per the bubbling rules explained under
actions
.Example
```app/router.js // ...
Router.map(function() { this.route('index'); });
export default Router; ```
```app/routes/application.js import Route from '@ember/routing/route'; import { action } from '@ember/object';
export default class ApplicationRoute extends Route { track(arg) { console.log(arg, 'was clicked'); } } ```
```app/routes/index.js import Route from '@ember/routing/route'; import { action } from '@ember/object';
export default class IndexRoute extends Route { trackIfDebug(arg) { if (debug) { this.send('track', arg); } } } ```
send
Parameter name
the name of the action to trigger
Parameter args
1.0.0
Modifiers
@public
property templateName
templateName: string;
The name of the template to use by default when rendering this route's template.
```app/routes/posts/list.js import Route from '@ember/routing/route';
export default class PostsListRoute extends Route { templateName = 'posts/list'; } ```
```app/routes/posts/index.js import PostsListRoute from '../posts/list';
export default class PostsIndexRoute extends PostsListRoute {}; ```
```app/routes/posts/archived.js import PostsListRoute from '../posts/list';
export default class PostsArchivedRoute extends PostsListRoute {}; ```
templateName String null 1.4.0
Modifiers
@public
method [RENDER]
[RENDER]: () => void;
this[RENDER]
is used to set up the rendering option for the outlet state. this[RENDER]
method activate
activate: (_transition: Transition) => void;
This hook is executed when the router enters the route. It is not executed when the model for the route changes.
activate
Parameter transition
1.0.0
Modifiers
@public
method afterModel
afterModel: ( _resolvedModel: Model | undefined, _transition: Transition) => unknown | Promise<unknown>;
This hook is called after this route's model has resolved. It follows identical async/promise semantics to
beforeModel
but is provided the route's resolved model in addition to thetransition
, and is therefore suited to performing logic that can only take place after the model has already resolved.```app/routes/posts.js import Route from '@ember/routing/route'; import { service } from '@ember/service';
export default class PostsRoute extends Route { router;
afterModel(posts, transition) { if (posts.get('length') === 1) { this.router.transitionTo('post.show', posts.get('firstObject')); } } } ```
Refer to documentation for
beforeModel
for a description of transition-pausing semantics when a promise is returned from this hook.afterModel
Parameter resolvedModel
the value returned from
model
, or its resolved value if it was a promiseParameter transition
{any | Promise} if the value returned from this hook is a promise, the transition will pause until the transition resolves. Otherwise, non-promise return values are not utilized in any way. 1.0.0
Modifiers
@public
method beforeModel
beforeModel: (_transition: Transition) => unknown | Promise<unknown>;
This hook is the first of the route entry validation hooks called when an attempt is made to transition into a route or one of its children. It is called before
model
andafterModel
, and is appropriate for cases when:1) A decision can be made to redirect elsewhere without needing to resolve the model first. 2) Any async operations need to occur first before the model is attempted to be resolved.
This hook is provided the current
transition
attempt as a parameter, which can be used to.abort()
the transition, save it for a later.retry()
, or retrieve values set on it from a previous hook. You can also just callrouter.transitionTo
to another route to implicitly abort thetransition
.You can return a promise from this hook to pause the transition until the promise resolves (or rejects). This could be useful, for instance, for retrieving async code from the server that is required to enter a route.
beforeModel
Parameter transition
{any | Promise} if the value returned from this hook is a promise, the transition will pause until the transition resolves. Otherwise, non-promise return values are not utilized in any way. 1.0.0
Modifiers
@public
method buildRouteInfoMetadata
buildRouteInfoMetadata: () => unknown;
Allows you to produce custom metadata for the route. The return value of this method will be attached to its corresponding RouteInfoWithAttributes object.
Example
```app/routes/posts/index.js import Route from '@ember/routing/route';
export default class PostsIndexRoute extends Route { buildRouteInfoMetadata() { return { title: 'Posts Page' } } } ```
```app/routes/application.js import Route from '@ember/routing/route'; import { service } from '@ember/service';
export default class ApplicationRoute extends Route { router
constructor() { super(...arguments);
this.router.on('routeDidChange', transition => { document.title = transition.to.metadata.title; // would update document's title to "Posts Page" }); } } ``` buildRouteInfoMetadata any 3.10.0
Modifiers
@public
method contextDidChange
contextDidChange: () => void;
Called when the context is changed by router.js.
contextDidChange
method controllerFor
controllerFor: { (name: string, _skipAssert: true): Controller | undefined; (name: string, _skipAssert?: false): Controller<unknown>;};
Returns the controller of the current route, or a parent (or any ancestor) route in a route hierarchy.
The controller instance must already have been created, either through entering the associated route or using
generateController
.```app/routes/post.js import Route from '@ember/routing/route';
export default class PostRoute extends Route { setupController(controller, post) { super.setupController(controller, post);
this.controllerFor('posts').set('currentPost', post); } } ```
controllerFor
Parameter name
the name of the route or controller {Controller | undefined} 1.0.0
Modifiers
@public
method deactivate
deactivate: (_transition?: Transition) => void;
This hook is executed when the router completely exits this route. It is not executed when the model for the route changes.
deactivate
Parameter transition
1.0.0
Modifiers
@public
method deserialize
deserialize: ( _params: Record<string, unknown>, transition: Transition) => Model | PromiseLike<Model> | undefined;
deserialize
Parameter params
the parameters extracted from the URL
Parameter transition
{any | Promise} the model for this route.
Router.js hook.
method deserializeQueryParam
deserializeQueryParam: ( value: unknown, _urlKey: string, defaultValueType: string) => {} | null | undefined;
Deserializes value of the query parameter based on defaultValueType
deserializeQueryParam
Parameter value
Parameter urlKey
Parameter defaultValueType
method enter
enter: (transition: Transition) => void;
enter
method exit
exit: (transition?: Transition) => void;
exit
method findModel
findModel: ( type: string, value: unknown) => Model | PromiseLike<Model> | undefined;
findModel
Parameter type
the model type
Parameter value
the value passed to find
method generateController
generateController: (name: string) => Controller<unknown>;
Generates a controller for a route.
Example
```app/routes/post.js import Route from '@ember/routing/route';
export default class Post extends Route { setupController(controller, post) { super.setupController(controller, post);
this.generateController('posts'); } } ```
generateController
Parameter name
the name of the controller
method intermediateTransitionTo
intermediateTransitionTo: (...args: NamedRouteArgs) => void;
Perform a synchronous transition into another route without attempting to resolve promises, update the URL, or abort any currently active asynchronous transitions (i.e. regular transitions caused by
transitionTo
or URL changes).This method is handy for performing intermediate transitions on the way to a final destination route, and is called internally by the default implementations of the
error
andloading
handlers.intermediateTransitionTo
Parameter name
the name of the route
Parameter models
the model(s) to be used while transitioning to the route. 1.2.0
Modifiers
@public
method model
model: ( params: Record<string, unknown>, transition: Transition) => Model | PromiseLike<Model> | undefined;
A hook you can implement to convert the URL into the model for this route.
```app/router.js // ...
Router.map(function() { this.route('post', { path: '/posts/:post_id' }); });
export default Router; ```
Note that for routes with dynamic segments, this hook is not always executed. If the route is entered through a transition (e.g. when using the
link-to
Handlebars helper or thetransitionTo
method of routes), and a model context is already provided this hook is not called.A model context does not include a primitive string or number, which does cause the model hook to be called.
Routes without dynamic segments will always execute the model hook.
```javascript // no dynamic segment, model hook always called this.router.transitionTo('posts');
// model passed in, so model hook not called thePost = store.findRecord('post', 1); this.router.transitionTo('post', thePost);
// integer passed in, model hook is called this.router.transitionTo('post', 1);
// model id passed in, model hook is called // useful for forcing the hook to execute thePost = store.findRecord('post', 1); this.router.transitionTo('post', thePost.id); ```
This hook follows the asynchronous/promise semantics described in the documentation for
beforeModel
. In particular, if a promise returned frommodel
fails, the error will be handled by theerror
hook onRoute
.Note that the legacy behavior of automatically defining a model hook when a dynamic segment ending in
_id
is present is [deprecated](https://deprecations.emberjs.com/v5.x#toc_deprecate-implicit-route-model). You should explicitly define a model hook whenever any segments are present.Example
```app/routes/post.js import Route from '@ember/routing/route'; import { service } from '@ember/service';
export default class PostRoute extends Route { store;
model(params) { return this.store.findRecord('post', params.post_id); } } ```
model
Parameter params
the parameters extracted from the URL
Parameter transition
{any | Promise} the model for this route. If a promise is returned, the transition will pause until the promise resolves, and the resolved value of the promise will be used as the model for this route. 1.0.0
Modifiers
@public
method modelFor
modelFor: (_name: string) => unknown | undefined;
Returns the resolved model of a parent (or any ancestor) route in a route hierarchy. During a transition, all routes must resolve a model object, and if a route needs access to a parent route's model in order to resolve a model (or just reuse the model from a parent), it can call
this.modelFor(theNameOfParentRoute)
to retrieve it. If the ancestor route's model was a promise, its resolved result is returned.Example
```app/router.js // ...
Router.map(function() { this.route('post', { path: '/posts/:post_id' }, function() { this.route('comments'); }); });
export default Router; ```
```app/routes/post/comments.js import Route from '@ember/routing/route';
export default class PostCommentsRoute extends Route { model() { let post = this.modelFor('post');
return post.comments; } } ```
modelFor
Parameter name
the name of the route {Object} the model object 1.0.0
Modifiers
@public
method paramsFor
paramsFor: (name: string) => Record<string, unknown>;
Returns a hash containing the parameters of an ancestor route.
You may notice that
this.paramsFor
sometimes works when referring to a child route, but this behavior should not be relied upon as only ancestor routes are certain to be loaded in time.Example
```app/router.js // ...
Router.map(function() { this.route('member', { path: ':name' }, function() { this.route('interest', { path: ':interest' }); }); }); ```
```app/routes/member.js import Route from '@ember/routing/route';
export default class MemberRoute extends Route { queryParams = { memberQp: { refreshModel: true } } } ```
```app/routes/member/interest.js import Route from '@ember/routing/route';
export default class MemberInterestRoute extends Route { queryParams = { interestQp: { refreshModel: true } }
model() { return this.paramsFor('member'); } } ```
If we visit
/turing/maths?memberQp=member&interestQp=interest
the model for themember.interest
route is a hash with:name
:turing
memberQp
:member
paramsFor
Parameter name
{Object} hash containing the parameters of the route
name
1.4.0Modifiers
@public
method redirect
redirect: (_model: Model, _transition: Transition) => void;
A hook you can implement to optionally redirect to another route.
Calling
this.router.transitionTo
from inside of theredirect
hook will abort the current transition (into the route that has implementedredirect
).redirect
andafterModel
behave very similarly and are called almost at the same time, but they have an important distinction when callingthis.router.transitionTo
to a child route of the current route. FromafterModel
, this new transition invalidates the current transition, causingbeforeModel
,model
, andafterModel
hooks to be called again. But the same transition started fromredirect
does _not_ invalidate the current transition. In other words, by the time theredirect
hook has been called, both the resolved model and the attempted entry into this route are considered fully validated.redirect
Parameter model
the model for this route
Parameter transition
the transition object associated with the current transition 1.0.0
Modifiers
@public
method refresh
refresh: () => Transition;
Refresh the model on this route and any child routes, firing the
beforeModel
,model
, andafterModel
hooks in a similar fashion to how routes are entered when transitioning in from other route. The current route params (e.g.article_id
) will be passed in to the respective model hooks, and if a different model is returned,setupController
and associated route hooks will re-fire as well.An example usage of this method is re-querying the server for the latest information using the same parameters as when the route was first entered.
Note that this will cause
model
hooks to fire even on routes that were provided a model object when the route was initially entered.refresh {Transition} the transition object associated with this attempted transition 1.4.0
Modifiers
@public
method resetController
resetController: ( _controller: Controller, _isExiting: boolean, _transition: Transition) => void;
A hook you can use to reset controller values either when the model changes or the route is exiting.
```app/routes/articles.js import Route from '@ember/routing/route';
export default class ArticlesRoute extends Route { resetController(controller, isExiting, transition) { if (isExiting && transition.targetName !== 'error') { controller.set('page', 1); } } } ```
resetController
Parameter controller
instance
Parameter isExiting
Parameter transition
1.7.0
Modifiers
@public
method serialize
serialize: (model: Model, params: string[]) => { [key: string]: unknown };
A hook you can implement to convert the route's model into parameters for the URL.
```app/router.js // ...
Router.map(function() { this.route('post', { path: '/posts/:post_id' }); });
```
```app/routes/post.js import Route from '@ember/routing/route';
export default class PostRoute extends Route { model({ post_id }) { // the server returns
{ id: 12 }
return fetch(/posts/${post_id}
; }serialize(model) { // this will make the URL
/posts/12
return { post_id: model.id }; } } ```The default
serialize
method will insert the model'sid
into the route's dynamic segment (in this case,:post_id
) if the segment contains '_id'. If the route has multiple dynamic segments or does not contain '_id',serialize
will returngetProperties(model, params)
This method is called when
transitionTo
is called with a context in order to populate the URL.serialize
Parameter model
the routes model
Parameter params
an Array of parameter names for the current route (in the example,
['post_id']
. {Object} the serialized parameters 1.0.0Modifiers
@public
method serializeQueryParam
serializeQueryParam: ( value: unknown, _urlKey: string, defaultValueType: string) => string | null | undefined;
Serializes value of the query parameter based on defaultValueType
serializeQueryParam
Parameter value
Parameter urlKey
Parameter defaultValueType
method serializeQueryParamKey
serializeQueryParamKey: (controllerPropertyName: string) => string;
Serializes the query parameter key
serializeQueryParamKey
Parameter controllerPropertyName
method setup
setup: (context: Model | undefined, transition: Transition) => void;
This hook is the entry point for router.js
setup
method setupController
setupController: ( controller: Controller, context: Model | undefined, _transition?: Transition) => void;
A hook you can use to setup the controller for the current route.
This method is called with the controller for the current route and the model supplied by the
model
hook.By default, the
setupController
hook sets themodel
property of the controller to the specifiedmodel
when it is notundefined
.If you implement the
setupController
hook in your Route, it will prevent this default behavior. If you want to preserve that behavior when implementing yoursetupController
function, make sure to callsuper
:```app/routes/photos.js import Route from '@ember/routing/route'; import { service } from '@ember/service';
export default class PhotosRoute extends Route { store;
model() { return this.store.findAll('photo'); }
setupController(controller, model) { super.setupController(controller, model);
this.controllerFor('application').set('showingPhotos', true); } } ```
The provided controller will be one resolved based on the name of this route.
If no explicit controller is defined, Ember will automatically create one.
As an example, consider the router:
```app/router.js // ...
Router.map(function() { this.route('post', { path: '/posts/:post_id' }); });
export default Router; ```
If you have defined a file for the post controller, the framework will use it. If it is not defined, a basic
Controller
instance would be used.Parameter controller
instance
Parameter model
Parameter transition
1.0.0
Example 1
Behavior of a basic Controller
```app/routes/post.js import Route from '@ember/routing/route';
export default class PostRoute extends Route { setupController(controller, model) { controller.set('model', model); } }); ```
setupController
Modifiers
@public
method teardownViews
teardownViews: () => void;
teardownViews
method willDestroy
willDestroy: () => void;
interface ExtendedInternalRouteInfo
interface ExtendedInternalRouteInfo<R extends Route> extends InternalRouteInfo<R> {}
interface Route
interface Route<Model = unknown> extends IRoute<Model>, ActionHandler, Evented {}
The
Route
class is used to define individual routes. Refer to the [routing guide](https://guides.emberjs.com/release/routing/) for documentation.Route EmberObject ActionHandler Evented 1.0.0
Modifiers
@public
method didTransition
didTransition: () => boolean | void;
The
didTransition
action is fired after a transition has successfully been completed. This occurs after the normal model hooks (beforeModel
,model
,afterModel
,setupController
) have resolved. ThedidTransition
action has no arguments, however, it can be useful for tracking page views or resetting state on the controller.```app/routes/login.js import Route from '@ember/routing/route'; import { action } from '@ember/object';
export default class LoginRoute extends Route { didTransition() { // your code there return true; // Bubble the didTransition event } } ```
didTransition 1.2.0
Modifiers
@public
method error
error: (error: Error, transition: Transition) => boolean | void;
When attempting to transition into a route, any of the hooks may return a promise that rejects, at which point an
error
action will be fired on the partially-entered routes, allowing for per-route error handling logic, or shared error handling logic defined on a parent route.Here is an example of an error handler that will be invoked for rejected promises from the various hooks on the route, as well as any unhandled errors from child routes:
```app/routes/admin.js import { reject } from 'rsvp'; import Route from '@ember/routing/route'; import { action } from '@ember/object'; import { service } from '@ember/service';
export default class AdminRoute extends Route { router;
beforeModel() { return reject('bad things!'); }
error(error, transition) { // Assuming we got here due to the error in
beforeModel
, // we can expect that error === "bad things!", // but a promise model rejecting would also // call this hook, as would any errors encountered // inafterModel
.// The
error
hook is also provided the failed //transition
, which can be stored and later //.retry()
d if desired.this.router.transitionTo('login'); } } ```
error
actions that bubble up all the way toApplicationRoute
will fire a default error handler that logs the error. You can specify your own global default error handler by overriding theerror
handler onApplicationRoute
:```app/routes/application.js import Route from '@ember/routing/route'; import { action } from '@ember/object';
export default class ApplicationRoute extends Route { error(error, transition) { this.controllerFor('banner').displayError(error.message); } } ``` error
Parameter error
Parameter transition
1.0.0
Modifiers
@public
method loading
loading: (transition: Transition, route: Route) => boolean | void;
The
loading
action is fired on the route when a route'smodel
hook returns a promise that is not already resolved. The currentTransition
object is the first parameter and the route that triggered the loading event is the second parameter.```app/routes/application.js import Route from '@ember/routing/route'; import { action } from '@ember/object';
export default class ApplicationRoute extends Route { loading(transition, route) { let controller = this.controllerFor('foo');
// The controller may not be instantiated when initially loading if (controller) { controller.currentlyLoading = true;
transition.finally(function() { controller.currentlyLoading = false; }); } } } ```
loading
Parameter transition
Parameter route
The route that triggered the loading event 1.2.0
Modifiers
@public
method willTransition
willTransition: (transition: Transition) => boolean | void;
The
willTransition
action is fired at the beginning of any attempted transition with aTransition
object as the sole argument. This action can be used for aborting, redirecting, or decorating the transition from the currently active routes.A good example is preventing navigation when a form is half-filled out:
```app/routes/contact-form.js import Route from '@ember/routing/route'; import { action } from '@ember/object';
export default class ContactFormRoute extends Route { willTransition(transition) { if (this.controller.get('userHasEnteredData')) { this.controller.displayNavigationConfirm(); transition.abort(); } } } ```
You can also redirect elsewhere by calling
this.router.transitionTo('elsewhere')
from withinwillTransition
. Note thatwillTransition
will not be fired for the redirectingtransitionTo
, sincewillTransition
doesn't fire when there is already a transition underway. If you want subsequentwillTransition
actions to fire for the redirecting transition, you must first explicitly calltransition.abort()
.To allow the
willTransition
event to continue bubbling to the parent route, usereturn true;
. When thewillTransition
method has a return value oftrue
then the parent route'swillTransition
method will be fired, enabling "bubbling" behavior for the event.willTransition
Parameter transition
1.0.0
Modifiers
@public
type QueryParamMeta
type QueryParamMeta = { qps: QueryParam[]; map: Record<string, QueryParam>; propertyNames: string[]; states: { inactive(prop: string, value: unknown): void; active(prop: string, value: unknown): any; allowOverrides(prop: string, value: unknown): any; };};
namespace @ember/routing/route-info
module '@ember/routing/route-info' {}
namespace @ember/routing/router
module '@ember/routing/router' {}
function triggerEvent
triggerEvent: <N extends 'willResolveModel' | 'error' | 'loading'>( this: EmberRouter, routeInfos: InternalRouteInfo<Route>[], ignoreFailure: boolean, name: N, args: OmitFirst<Parameters<(typeof defaultActionHandlers)[N]>>) => void;
class EmberRouter
class EmberRouter extends EmberRouter_base implements Evented {}
The
EmberRouter
class manages the application state and URLs. Refer to the [routing guide](https://guides.emberjs.com/release/routing/) for documentation.EmberRouter EmberObject Evented
Modifiers
@public
constructor
constructor(owner?: Owner);
property currentPath
currentPath: string;
property currentRoute
currentRoute: any;
property currentRouteName
currentRouteName: string;
property currentState
currentState: RouterState;
property currentURL
currentURL: string;
property didTransition
didTransition: ( this: EmberRouter, infos: InternalRouteInfo<Route<unknown>>[]) => void;
Handles updating the paths and notifying any listeners of the URL change.
Triggers the router level
didTransition
hook.For example, to notify google analytics when the route changes, you could use this hook. (Note: requires also including GA scripts, etc.)
```javascript import config from './config/environment'; import EmberRouter from '@ember/routing/router'; import { service } from '@ember/service';
let Router = EmberRouter.extend({ location: config.locationType,
router: service(),
didTransition: function() { this._super(...arguments);
ga('send', 'pageview', { page: this.router.currentURL, title: this.router.currentRouteName, }); } }); ```
didTransition 1.2.0
property has
has: (name: string) => boolean;
property location
location: string | EmberLocation;
The
location
property determines the type of URL's that your application will use.The following location types are currently available:
history
- use the browser's history API to make the URLs look just like any standard URLhash
- use#
to separate the server part of the URL from the Ember part:/blog/#/posts/new
none
- do not store the Ember URL in the actual browser URL (mainly used for testing)auto
- use the best option based on browser capabilities:history
if possible, thenhash
if possible, otherwisenone
This value is defaulted to
history
by thelocationType
setting of/config/environment.js
location 'hash'
See Also
{Location}
Modifiers
@public
property off
off: (name: string, method: string | ((...args: any[]) => void)) => this;
property on
on: (name: string, method: string | ((...args: any[]) => void)) => this;
property one
one: (name: string, method: string | ((...args: any[]) => void)) => this;
property rootURL
rootURL: string;
Represents the URL of the root of the application, often '/'. This prefix is assumed on all routes defined on this router.
rootURL '/'
Modifiers
@public
property targetState
targetState: RouterState;
property trigger
trigger: (name: string, ...args: any[]) => unknown;
property url
url: string;
Represents the current URL.
url {String}
property willTransition
willTransition: ( this: EmberRouter, oldInfos: InternalRouteInfo<Route<unknown>>[], newInfos: InternalRouteInfo<Route<unknown>>[]) => void;
Handles notifying any listeners of an impending URL change.
Triggers the router level
willTransition
hook.willTransition 1.11.0
method generate
generate: ( name: string, ...args: ModelFor<Route>[] | [...ModelFor<Route>[], RouteOptions]) => string;
method handleURL
handleURL: (url: string) => any;
method hasRoute
hasRoute: (route: string) => boolean;
Does this router instance have the given route.
hasRoute {Boolean}
method intermediateTransitionTo
intermediateTransitionTo: (name: string, ...args: any[]) => void;
method isActive
isActive: (routeName: string) => boolean;
Determines if the supplied route is currently active.
isActive
Parameter routeName
{Boolean}
method isActiveIntent
isActiveIntent: ( routeName: string, models: ModelFor<Route>[], queryParams: Record<string, unknown>) => boolean;
An alternative form of
isActive
that doesn't require manual concatenation of the arguments into a single array.isActiveIntent
Parameter routeName
Parameter models
Parameter queryParams
{Boolean} 1.7.0
method map
static map: (callback: DSLCallback) => typeof EmberRouter;
The
Router.map
function allows you to define mappings from URLs to routes in your application. These mappings are defined within the supplied callback function usingthis.route
.The first parameter is the name of the route which is used by default as the path name as well.
The second parameter is the optional options hash. Available options are:
path
: allows you to provide your own path as well as mark dynamic segments.resetNamespace
: false by default; when nesting routes, ember will combine the route names to form the fully-qualified route name, which is used with{{link-to}}
or manually transitioning to routes. SettingresetNamespace: true
will cause the route not to inherit from its parent route's names. This is handy for preventing extremely long route names. Keep in mind that the actual URL path behavior is still retained.The third parameter is a function, which can be used to nest routes. Nested routes, by default, will have the parent route tree's route name and path prepended to it's own.
```app/router.js Router.map(function(){ this.route('post', { path: '/post/:post_id' }, function() { this.route('edit'); this.route('comments', { resetNamespace: true }, function() { this.route('new'); }); }); }); ```
map
Parameter callback
Modifiers
@public
method replaceWith
replaceWith: (...args: RouteArgs) => Transition;
Similar to
transitionTo
, but instead of adding the destination to the browser's URL history, it replaces the entry for the current route. When the user clicks the "back" button in the browser, there will be fewer steps. This is most commonly used to manage redirects in a way that does not cause confusing additions to the user's browsing history.replaceWith
Parameter name
the name of the route or a URL
Parameter models
the model(s) or identifier(s) to be used while transitioning to the route.
Parameter options
optional hash with a queryParams property containing a mapping of query parameters {Transition} the transition object associated with this attempted transition
Modifiers
@public
method reset
reset: () => void;
Resets the state of the router by clearing the current route handlers and deactivating them.
reset
method send
send: (name: string, ...args: any[]) => void;
method setupRouter
setupRouter: () => boolean;
method startRouting
startRouting: () => void;
Initializes the current router instance and sets up the change handling event listeners used by the instances
location
implementation.A property named
initialURL
will be used to determine the initial URL. If no value is found/
will be used.startRouting
method transitionTo
transitionTo: (...args: RouteArgs) => Transition;
Transition the application into another route. The route may be either a single route or route path:
transitionTo
Parameter name
the name of the route or a URL
Parameter models
the model(s) or identifier(s) to be used while transitioning to the route.
Parameter options
optional hash with a queryParams property containing a mapping of query parameters {Transition} the transition object associated with this attempted transition
Modifiers
@public
method willDestroy
willDestroy: () => void;
interface QueryParam
interface QueryParam {}
property controllerName
controllerName: string;
property defaultValue
defaultValue: unknown;
property parts
parts?: string[];
property prop
prop: string;
property route
route: Route;
property scope
scope: string;
property scopedPropertyName
scopedPropertyName: string;
property serializedDefaultValue
serializedDefaultValue: string | null | undefined;
property serializedValue
serializedValue: string | null | undefined;
property type
type: string;
property undecoratedDefaultValue
undecoratedDefaultValue: unknown;
property urlKey
urlKey: string;
property values
values: {} | null;
namespace @ember/routing/router-service
module '@ember/routing/router-service' {}
variable ROUTER
const ROUTER: Symbol;
class RouterService
class RouterService extends RouterService_base {}
property [ROUTER]
[ROUTER]?: EmberRouter;
property currentRoute
readonly currentRoute: any;
The
currentRoute
property contains metadata about the current leaf route. It returns aRouteInfo
object that has information like the route name, params, query params and more.See [RouteInfo](/ember/release/classes/RouteInfo) for more info.
This property is guaranteed to change whenever a route transition happens (even when that transition only changes parameters and doesn't change the active route).
Usage example: ```app/components/header.js import Component from '@glimmer/component'; import { service } from '@ember/service'; import { notEmpty } from '@ember/object/computed';
export default class extends Component { router;
@notEmpty('router.currentRoute.child') isChildRoute; }); ```
currentRoute RouteInfo
Modifiers
@public
property currentRouteName
readonly currentRouteName: string;
Name of the current route.
This property represents the logical name of the route, which is dot separated. For the following router:
```app/router.js Router.map(function() { this.route('about'); this.route('blog', function () { this.route('post', { path: ':post_id' }); }); }); ```
It will return:
index
when you visit/
about
when you visit/about
blog.index
when you visit/blog
blog.post
when you visit/blog/some-post-id
currentRouteName {String | null}
Modifiers
@public
property currentURL
readonly currentURL: string;
Current URL for the application.
This property represents the URL path for this route. For the following router:
```app/router.js Router.map(function() { this.route('about'); this.route('blog', function () { this.route('post', { path: ':post_id' }); }); }); ```
It will return:
/
when you visit/
/about
when you visit/about
/blog
when you visit/blog
/blog/some-post-id
when you visit/blog/some-post-id
currentURL String
Modifiers
@public
property location
readonly location: string | Location;
The
location
property returns what implementation of thelocation
API your application is using, which determines what type of URL is being used.See [Location](/ember/release/classes/Location) for more information.
To force a particular
location
API implementation to be used in your application you can set a location type on yourconfig/environment
. For example, to set thehistory
type:```config/environment.js 'use strict';
module.exports = function(environment) { let ENV = { modulePrefix: 'router-service', environment, rootURL: '/', locationType: 'history', ... } } ```
The following location types are available by default:
hash
,history
,none
.See [HashLocation](/ember/release/classes/HashLocation). See [HistoryLocation](/ember/release/classes/HistoryLocation). See [NoneLocation](/ember/release/classes/NoneLocation).
location 'hash'
See Also
{Location}
Modifiers
@public
property rootURL
readonly rootURL: string;
The
rootURL
property represents the URL of the root of the application, '/' by default. This prefix is assumed on all routes defined on this app.If you change the
rootURL
in your environment configuration like so:```config/environment.js 'use strict';
module.exports = function(environment) { let ENV = { modulePrefix: 'router-service', environment, rootURL: '/my-root', … } ] ```
This property will return
/my-root
.rootURL '/'
Modifiers
@public
method isActive
isActive: (...args: RouteArgs) => boolean;
Returns
true
ifrouteName/models/queryParams
is the active route, wheremodels
andqueryParams
are optional. See [model](api/ember/release/classes/Route/methods/model?anchor=model) and [queryParams](/api/ember/3.7/classes/Route/properties/queryParams?anchor=queryParams) for more information about these arguments.In the following example,
isActive
will returntrue
if the current route is/posts
.```app/components/posts.js import Component from '@glimmer/component'; import { service } from '@ember/service';
export default class extends Component { router;
displayComments() { return this.router.isActive('posts'); } }); ```
The next example includes a dynamic segment, and will return
true
if the current route is/posts/1
, assuming the post has an id of 1:```app/components/posts.js import Component from '@glimmer/component'; import { service } from '@ember/service';
export default class extends Component { router;
displayComments(post) { return this.router.isActive('posts', post.id); } }); ```
Where
post.id
is the id of a specific post, which is represented in the route as /posts/[post.id]. Ifpost.id
is equal to 1, then isActive will return true if the current route is /posts/1, and false if the route is anything else.isActive
Parameter routeName
the name of the route
Parameter models
the model(s) or identifier(s) to be used when determining the active route.
Parameter options
optional hash with a queryParams property containing a mapping of query parameters {boolean} true if the provided routeName/models/queryParams are active
Modifiers
@public
method recognize
recognize: (url: string) => RouteInfo | null;
Takes a string URL and returns a
RouteInfo
for the leafmost route represented by the URL. Returnsnull
if the URL is not recognized. This method expects to receive the actual URL as seen by the browser including the app'srootURL
.See [RouteInfo](/ember/release/classes/RouteInfo) for more info.
In the following example
recognize
is used to verify if a path belongs to our application before transitioning to it.``` import Component from '@ember/component'; import { service } from '@ember/service';
export default class extends Component { router; path = '/';
click() { if (this.router.recognize(this.path)) { this.router.transitionTo(this.path); } } } ```
recognize
Parameter url
{RouteInfo | null}
Modifiers
@public
method recognizeAndLoad
recognizeAndLoad: (url: string) => Promise<RouteInfoWithAttributes>;
Takes a string URL and returns a promise that resolves to a
RouteInfoWithAttributes
for the leafmost route represented by the URL. The promise rejects if the URL is not recognized or an unhandled exception is encountered. This method expects to receive the actual URL as seen by the browser including the app'srootURL
.recognizeAndLoad
Parameter url
{RouteInfo}
Modifiers
@public
method refresh
refresh: (pivotRouteName?: string) => Transition;
Refreshes all currently active routes, doing a full transition. If a route name is provided and refers to a currently active route, it will refresh only that route and its descendents. Returns a promise that will be resolved once the refresh is complete. All resetController, beforeModel, model, afterModel, redirect, and setupController hooks will be called again. You will get new data from the model hook.
refresh
Parameter routeName
the route to refresh (along with all child routes) Transition
Modifiers
@public
method replaceWith
replaceWith: (...args: RouteArgs) => Transition;
Similar to
transitionTo
, but instead of adding the destination to the browser's URL history, it replaces the entry for the current route. When the user clicks the "back" button in the browser, there will be fewer steps. This is most commonly used to manage redirects in a way that does not cause confusing additions to the user's browsing history.Calling
replaceWith
from the Router service will cause default query parameter values to be included in the URL. This behavior is different from callingreplaceWith
on a route. See the [Router Service RFC](https://github.com/emberjs/rfcs/blob/master/text/0095-router-service.md#query-parameter-semantics) for more info.Usage example:
```app/routes/application.js import Route from '@ember/routing/route'; import { service } from '@ember/service';
export default class extends Route { router; beforeModel() { if (!authorized()){ this.router.replaceWith('unauthorized'); } } }); ```
replaceWith
Parameter routeNameOrUrl
the name of the route or a URL of the desired destination
Parameter models
the model(s) or identifier(s) to be used while transitioning to the route i.e. an object of params to pass to the destination route
Parameter options
optional hash with a queryParams property containing a mapping of query parameters {Transition} the transition object associated with this attempted transition
Modifiers
@public
method transitionTo
transitionTo: (...args: RouteArgs) => Transition;
Transition the application into another route. The route may be either a single route or route path:
Calling
transitionTo
from the Router service will cause default query parameter values to be included in the URL. This behavior is different from callingtransitionTo
on a route ortransitionToRoute
on a controller. See the [Router Service RFC](https://github.com/emberjs/rfcs/blob/master/text/0095-router-service.md#query-parameter-semantics) for more info.In the following example we use the Router service to navigate to a route with a specific model from a Component in the first action, and in the second we trigger a query-params only transition.
```app/components/example.js import Component from '@glimmer/component'; import { action } from '@ember/object'; import { service } from '@ember/service';
export default class extends Component { router;
goToComments(post) { this.router.transitionTo('comments', post); }
fetchMoreComments(latestComment) { this.router.transitionTo({ queryParams: { commentsAfter: latestComment } }); } } ```
transitionTo
Parameter routeNameOrUrl
the name of the route or a URL
Parameter models
the model(s) or identifier(s) to be used while transitioning to the route.
Parameter options
optional hash with a queryParams property containing a mapping of query parameters. May be supplied as the only parameter to trigger a query-parameter-only transition. {Transition} the transition object associated with this attempted transition
Modifiers
@public
method urlFor
urlFor: <R extends Route<unknown>>( routeName: string, ...args: ModelFor<R>[] | [...ModelFor<R>[], RouteOptions]) => string;
Generate a URL based on the supplied route name and optionally a model. The URL is returned as a string that can be used for any purpose.
In this example, the URL for the
author.books
route for a given author is copied to the clipboard.```app/templates/application.hbs <CopyLink @author={{hash id="tomster" name="Tomster"}} /> ```
```app/components/copy-link.js import Component from '@glimmer/component'; import { service } from '@ember/service'; import { action } from '@ember/object';
export default class CopyLinkComponent extends Component { router; clipboard;
copyBooksURL() { if (this.author) { const url = this.router.urlFor('author.books', this.args.author); this.clipboard.set(url); // Clipboard now has /author/tomster/books } } } ```
Just like with
transitionTo
andreplaceWith
,urlFor
can also handle query parameters.```app/templates/application.hbs <CopyLink @author={{hash id="tomster" name="Tomster"}} /> ```
```app/components/copy-link.js import Component from '@glimmer/component'; import { service } from '@ember/service'; import { action } from '@ember/object';
export default class CopyLinkComponent extends Component { router; clipboard;
copyOnlyEmberBooksURL() { if (this.author) { const url = this.router.urlFor('author.books', this.author, { queryParams: { filter: 'emberjs' } }); this.clipboard.set(url); // Clipboard now has /author/tomster/books?filter=emberjs } } } ```
urlFor
Parameter routeName
the name of the route
Parameter models
the model(s) for the route.
Parameter options
optional hash with a queryParams property containing a mapping of query parameters {String} the string representing the generated URL
Modifiers
@public
method willDestroy
willDestroy: () => void;
interface RouterService
interface RouterService extends Evented {}
The Router service is the public API that provides access to the router.
The immediate benefit of the Router service is that you can inject it into components, giving them a friendly way to initiate transitions and ask questions about the current global router state.
In this example, the Router service is injected into a component to initiate a transition to a dedicated route:
```app/components/example.js import Component from '@glimmer/component'; import { action } from '@ember/object'; import { service } from '@ember/service';
export default class ExampleComponent extends Component { router;
next() { this.router.transitionTo('other.route'); } } ```
Like any service, it can also be injected into helpers, routes, etc.
Service RouterService
Modifiers
@public
method on
on: ( eventName: 'routeWillChange' | 'routeDidChange', callback: (transition: Transition) => void) => this;
namespace @ember/routing/transition
module '@ember/routing/transition' {}
namespace @ember/runloop
module '@ember/runloop' {}
function begin
begin: () => void;
Begins a new RunLoop. Any deferred actions invoked after the begin will be buffered until you invoke a matching call to
end()
. This is a lower-level way to use a RunLoop instead of usingrun()
.```javascript import { begin, end } from '@ember/runloop';
begin(); // code to be executed within a RunLoop end(); ```
begin @ember/runloop {void}
Modifiers
@public
function bind
bind: { < T, F extends (this: T, ...args: any[]) => any, A extends PartialParams<Parameters<F>> >( target: T, method: F, ...args: A ): (...args: RemainingParams<A, Parameters<F>>) => ReturnType<F> | void; <F extends AnyFn, A extends PartialParams<Parameters<F>>>( method: F, ...args: A ): (...args: RemainingParams<A, Parameters<F>>) => void | ReturnType<F>; < T, U extends keyof T, A extends T[U] extends AnyFn ? PartialParams<Parameters<T[U]>> : [] >( target: T, method: U, ...args: A ): T[U] extends AnyFn ? (...args: RemainingParams<A, Parameters<T[U]>>) => void | ReturnType<T[U]> : never; <T, M extends keyof T & PropertyKey>(target: T, methodName: M, ...args: any[]): ( ...args: any[] ) => unknown;};
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.
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:
```app/components/rich-text-editor.js import Component from '@ember/component'; import { on } from '@ember/object/evented'; import { bind } from '@ember/runloop';
export default Component.extend({ initializeTinyMCE: on('didInsertElement', function() { tinymce.init({ selector: '#' + this.$().prop('id'), setup: bind(this, this.setupEditor) }); }),
didInsertElement() { tinymce.init({ selector: '#' + this.$().prop('id'), setup: bind(this, this.setupEditor) }); }
setupEditor(editor) { this.set('editor', editor);
editor.on('change', function() { console.log('content changed!'); }); } }); ```
In this example, we use
bind
to bind the setupEditor method to the context of the RichTextEditor component and to have the invocation of that method be safely handled and executed by the Ember run loop.bind @ember/runloop
Parameter target
target of method to call
Parameter 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.
Parameter args
Any additional arguments you wish to pass to the method. {Function} returns a new function that will always have a particular context 1.4.0
Modifiers
@public
function cancel
cancel: (timer?: Timer) => boolean;
Cancels a scheduled item. Must be a value returned by
later()
,once()
,scheduleOnce()
,next()
,debounce()
, orthrottle()
.```javascript import { next, cancel, later, scheduleOnce, once, throttle, debounce } from '@ember/runloop';
let runNext = next(myContext, function() { // will not be executed });
cancel(runNext);
let runLater = later(myContext, function() { // will not be executed }, 500);
cancel(runLater);
let runScheduleOnce = scheduleOnce('afterRender', myContext, function() { // will not be executed });
cancel(runScheduleOnce);
let runOnce = once(myContext, function() { // will not be executed });
cancel(runOnce);
let throttle = throttle(myContext, function() { // will not be executed }, 1, false);
cancel(throttle);
let debounce = debounce(myContext, function() { // will not be executed }, 1);
cancel(debounce);
let debounceImmediate = 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 canceled cancel(debounceImmediate); ```
cancel @ember/runloop
Parameter timer
Timer object to cancel {Boolean} true if canceled or false/undefined if it wasn't found
Modifiers
@public
function debounce
debounce: { <F extends AnyFn>( method: F, ...args: [...args: Parameters<F>, wait: string | number, immediate?: boolean] ): Timer; <T, F extends (this: T, ...args: any[]) => any>( target: T, method: F, ...args: [...args: Parameters<F>, wait: string | number, immediate?: boolean] ): Timer; <T, U extends keyof T>( target: T, method: U, ...args: [ ...args: T[U] extends AnyFn ? Parameters<T[U]> : [], wait: string | number, immediate?: boolean ] ): 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 import { debounce } from '@ember/runloop';
function whoRan() { console.log(this.name + ' ran.'); }
let myContext = { name: 'debounce' };
debounce(myContext, whoRan, 150);
// less than 150ms passes 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 import { debounce } from '@ember/runloop';
function whoRan() { console.log(this.name + ' ran.'); }
let myContext = { name: 'debounce' };
debounce(myContext, whoRan, 150, true);
// console logs 'debounce ran.' one time immediately. // 100ms passes debounce(myContext, whoRan, 150, true);
// 150ms passes and nothing else is logged to the console and // the debouncee is no longer being watched 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 ```
debounce @ember/runloop
Parameter target
target of method to invoke
Parameter 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.
Parameter args
Optional arguments to pass to the timeout.
Parameter wait
Number of milliseconds to wait.
Parameter immediate
Trigger the function on the leading instead of the trailing edge of the wait interval. Defaults to false. {Array} Timer information for use in canceling, see
cancel
.Modifiers
@public
function end
end: () => void;
Ends a RunLoop. This must be called sometime after you call
begin()
to flush any deferred actions. This is a lower-level way to use a RunLoop instead of usingrun()
.```javascript import { begin, end } from '@ember/runloop';
begin(); // code to be executed within a RunLoop end(); ```
end @ember/runloop {void}
Modifiers
@public
function join
join: { <F extends AnyFn>(method: F, ...args: Parameters<F>): ReturnType<F> | void; <T, F extends (this: T, ...args: any[]) => any>( target: T, method: F, ...args: Parameters<F> ): void | ReturnType<F>; <T, U extends keyof T>( target: T, method: U, ...args: T[U] extends AnyFn ? Parameters<T[U]> : [] ): T[U] extends AnyFn ? void | ReturnType<T[U]> : void;};
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 import { join } from '@ember/runloop';
join(function() { // creates a new run-loop }); ```
Alternatively, if called within an existing run loop:
```javascript import { run, join } from '@ember/runloop';
run(function() { // creates a new run-loop
join(function() { // joins with the existing run-loop, and queues for invocation on // the existing run-loops action queue. }); }); ```
join @ember/runloop
Parameter target
target of method to call
Parameter 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.
Parameter args
Any additional arguments you wish to pass to the method. {Object} Return value from invoking the passed function. Please note, when called within an existing loop, no return value is possible.
Modifiers
@public
function later
later: { <T, F extends (this: T, ...args: any[]) => any>( target: T, method: F, ...args: [...args: Parameters<F>, wait: string | number] ): Timer; <F extends AnyFn>( method: F, ...args: [...args: Parameters<F>, wait: string | number] ): Timer; <T, U extends keyof T>( target: T, method: U, ...args: [ ...args: T[U] extends AnyFn ? Parameters<T[U]> : [], wait: string | number ] ): Timer;};
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 import { later } from '@ember/runloop';
later(myContext, function() { // code here will execute within a RunLoop in about 500ms with this == myContext }, 500); ```
later @ember/runloop
Parameter target
target of method to invoke
Parameter method
The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked.
Parameter args
Optional arguments to pass to the timeout.
Parameter wait
Number of milliseconds to wait. {*} Timer information for use in canceling, see
cancel
.Modifiers
@public
function next
next: { <F extends AnyFn>(method: F, ...args: Parameters<F>): Timer; <T, F extends (this: T, ...args: any[]) => any>( target: T, method: F, ...args: Parameters<F> ): Timer; <T, U extends keyof T>( target: T, method: U, ...args: T[U] extends AnyFn ? Parameters<T[U]> : [] ): Timer;};
Schedules an item to run from within a separate run loop, after control has been returned to the system. This is equivalent to calling
later
with a wait time of 1ms.```javascript import { next } from '@ember/runloop';
next(myContext, function() { // code to be executed in the next run loop, // which will be scheduled after the current one }); ```
Multiple operations scheduled with
next
will coalesce into the same later run loop, along with any other operations scheduled bylater
that expire right around the same time thatnext
operations will fire.Note that there are often alternatives to using
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 theafterRender
run loop queue (added by theember-views
package, along with the precedingrender
queue where all the DOM element operations happen).Example:
```app/components/my-component.js import Component from '@ember/component'; import { scheduleOnce } from '@ember/runloop';
export Component.extend({ didInsertElement() { this._super(...arguments); scheduleOnce('afterRender', this, 'processChildElements'); },
processChildElements() { // ... do something with component's child component // elements after they've finished rendering, which // can't be done within this component'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
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
next
introduces an element of non-determinism, which can make things much harder to test, due to its reliance onsetTimeout
; it's much harder to guarantee the order of scheduled operations when they are scheduled outside of the current run loop, i.e. withnext
.next @ember/runloop
Parameter target
target of method to invoke
Parameter method
The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked.
Parameter args
Optional arguments to pass to the timeout. {Object} Timer information for use in canceling, see
cancel
.Modifiers
@public
function once
once: { <F extends AnyFn>(method: F, ...args: Parameters<F>): Timer; <T, F extends (this: T, ...args: any[]) => any>( target: T, method: F, ...args: Parameters<F> ): Timer; <T, U extends keyof T>( target: T, method: U, ...args: T[U] extends AnyFn ? Parameters<T[U]> : [] ): Timer;};
Schedule a function to run one time during the current RunLoop. This is equivalent to calling
scheduleOnce
with the "actions" queue.once @ember/runloop
Parameter target
The target of the method to invoke.
Parameter method
The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked.
Parameter args
Optional arguments to pass to the timeout. {Object} Timer information for use in canceling, see
cancel
.Modifiers
@public
function run
run: { <F extends () => any>(method: F): ReturnType<F>; <F extends AnyFn>(method: F, ...args: Parameters<F>): ReturnType<F>; <T, F extends (this: T, ...args: any[]) => any>( target: T, method: F, ...args: Parameters<F> ): ReturnType<F>; <T, U extends keyof T>( target: T, method: U, ...args: T[U] extends AnyFn ? Parameters<T[U]> : [] ): T[U] extends AnyFn ? ReturnType<T[U]> : unknown;};
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 import { run } from '@ember/runloop';
run(function() { // code to be executed within a RunLoop }); ``` run @ember/runloop
Parameter target
target of method to call
Parameter 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.
Parameter args
Any additional arguments you wish to pass to the method. {Object} return value from invoking the passed function.
Modifiers
@public
function schedule
schedule: { <F extends AnyFn>(queueName: string, method: F, ...args: Parameters<F>): Timer; <T, F extends (this: T, ...args: any[]) => any>( queueName: string, target: T, method: F, ...args: Parameters<F> ): Timer; <T, U extends keyof T>( queueName: string, target: T, method: U, ...args: T[U] extends AnyFn ? Parameters<T[U]> : [] ): Timer;};
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
queues
property.```javascript import { schedule } from '@ember/runloop';
schedule('afterRender', this, function() { // this will be executed in the 'afterRender' queue console.log('scheduled on afterRender queue'); });
schedule('actions', this, function() { // this will be executed in the 'actions' queue 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 actions queue // scheduled on afterRender queue ```
schedule @ember/runloop
Parameter queue
The name of the queue to schedule against. Default queues is 'actions'
Parameter target
target object to use as the context when invoking a method.
Parameter 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.
Parameter arguments
Optional arguments to be passed to the queued method. {*} Timer information for use in canceling, see
cancel
.Modifiers
@public
function scheduleOnce
scheduleOnce: { <F extends AnyFn>(queueName: string, method: F, ...args: Parameters<F>): Timer; <T, F extends (this: T, ...args: any[]) => any>( queueName: string, target: T, method: F, ...args: Parameters<F> ): Timer; <T, U extends keyof T>( queueName: string, target: T, method: U, ...args: T[U] extends AnyFn ? Parameters<T[U]> : [] ): Timer;};
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 import { run, scheduleOnce } from '@ember/runloop';
function sayHi() { console.log('hi'); }
run(function() { scheduleOnce('afterRender', myContext, sayHi); scheduleOnce('afterRender', myContext, sayHi); // sayHi will only be executed once, in the afterRender queue of the RunLoop }); ```
Also note that for
scheduleOnce
to prevent additional calls, you need to pass the same function instance. The following case works as expected:```javascript function log() { console.log('Logging only once'); }
function scheduleIt() { scheduleOnce('actions', myContext, log); }
scheduleIt(); scheduleIt(); ```
But this other case will schedule the function multiple times:
```javascript import { scheduleOnce } from '@ember/runloop';
function scheduleIt() { scheduleOnce('actions', myContext, function() { console.log('Closure'); }); }
scheduleIt(); scheduleIt();
// "Closure" will print twice, even though we're using
scheduleOnce
, // because the function we pass to it won't match the // previously scheduled operation. ```Available queues, and their order, can be found at
queues
scheduleOnce @ember/runloop
Parameter queue
The name of the queue to schedule against. Default queues is 'actions'.
Parameter target
The target of the method to invoke.
Parameter method
The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked.
Parameter args
Optional arguments to pass to the timeout. {Object} Timer information for use in canceling, see
cancel
.Modifiers
@public
function throttle
throttle: { <F extends AnyFn>( method: F, ...args: [ ...args: Parameters<F>, wait?: string | number, immediate?: boolean ] ): Timer; <T, F extends (this: T, ...args: any[]) => any>( target: T, method: F, ...args: [ ...args: Parameters<F>, wait?: string | number, immediate?: boolean ] ): Timer; <T, U extends keyof T>( target: T, method: U, ...args: [ ...args: T[U] extends AnyFn ? Parameters<T[U]> : [], wait?: string | number, immediate?: boolean ] ): Timer;};
Ensure that the target method is never called more frequently than the specified spacing period. The target method is called immediately.
```javascript import { throttle } from '@ember/runloop';
function whoRan() { console.log(this.name + ' ran.'); }
let myContext = { name: 'throttle' };
throttle(myContext, whoRan, 150); // whoRan is invoked with context myContext // console logs 'throttle ran.'
// 50ms passes throttle(myContext, whoRan, 150);
// 50ms passes throttle(myContext, whoRan, 150);
// 150ms passes throttle(myContext, whoRan, 150); // whoRan is invoked with context myContext // console logs 'throttle ran.' ```
throttle @ember/runloop
Parameter target
target of method to invoke
Parameter 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.
Parameter args
Optional arguments to pass to the timeout.
Parameter spacing
Number of milliseconds to space out requests.
Parameter immediate
Trigger the function on the leading instead of the trailing edge of the wait interval. Defaults to true. {Array} Timer information for use in canceling, see
cancel
.Modifiers
@public
namespace @ember/runloop/-private/backburner
module '@ember/runloop/-private/backburner' {}
type DebugInfo
type DebugInfo = ReturnType<Backburner['getDebugInfo']>;
namespace @ember/service
module '@ember/service' {}
function inject
inject: { (name: string): PropertyDecorator; (args_0: object, args_1: string): void; ( target: object, propertyName: string, descriptor?: PropertyDescriptor & { initializer?: any } ): PropertyDescriptor & { initializer?: any }; (): PropertyDecorator;};
inject 1.10.0 @ember/service
Parameter name
(optional) name of the service to inject, defaults to the property's name {ComputedDecorator} injection decorator instance
Modifiers
@public
function service
service: { (name: string): PropertyDecorator; (args_0: object, args_1: string): void; ( target: object, propertyName: string, descriptor?: PropertyDescriptor & { initializer?: any } ): PropertyDescriptor & { initializer?: any }; (): PropertyDecorator;};
Creates a property that lazily looks up a service in the container. There are no restrictions as to what objects a service can be injected into.
Example:
```app/routes/application.js import Route from '@ember/routing/route'; import { service } from '@ember/service';
export default class ApplicationRoute extends Route { @service('auth') authManager;
model() { return this.authManager.findCurrentUser(); } } ```
Classic Class Example:
```app/routes/application.js import Route from '@ember/routing/route'; import { service } from '@ember/service';
export default Route.extend({ authManager: service('auth'),
model() { return this.get('authManager').findCurrentUser(); } }); ```
This example will create an
authManager
property on the application route that looks up theauth
service in the container, making it easily accessible in themodel
hook.service 4.1.0 @ember/service
Parameter name
(optional) name of the service to inject, defaults to the property's name {ComputedDecorator} injection decorator instance
Modifiers
@public
class Service
class Service extends FrameworkObject {}
Service EmberObject 1.10.0
Modifiers
@public
property isServiceFactory
static isServiceFactory: boolean;
interface Registry
interface Registry extends Record<string, object | undefined> {}
A type registry for Ember
Service
s. Meant to be declaration-merged so string lookups resolve to the correct type.Blueprints should include such a declaration merge for TypeScript:
```ts import Service from '@ember/service';
export default class ExampleService extends Service { // ... }
declare module '@ember/service' { export interface Registry { example: ExampleService; } } ```
Then
@service
can check that the service is registered correctly, and APIs likeowner.lookup('service:example')
can returnExampleService
.
namespace @ember/template
module '@ember/template' {}
function htmlSafe
htmlSafe: (str: string) => SafeString;
Use this method to indicate that a string should be rendered as HTML when the string is used in a template. To say this another way, strings marked with
htmlSafe
will not be HTML escaped.A word of warning - The
htmlSafe
method does not make the string safe; it only tells the framework to treat the string as if it is safe to render as HTML. If a string contains user inputs or other untrusted data, you must sanitize the string before using thehtmlSafe
method. Otherwise your code is vulnerable to [Cross-Site Scripting](https://owasp.org/www-community/attacks/DOM_Based_XSS). There are many open source sanitization libraries to choose from, both for front end and server-side sanitization.```javascript import { htmlSafe } from '@ember/template';
const someTrustedOrSanitizedString = "Hello!"
htmlSafe(someTrustedorSanitizedString) ```
htmlSafe @ember/template
Parameter str
The string to treat as trusted. {SafeString} A string that will not be HTML escaped by Handlebars.
Modifiers
@public
function isHTMLSafe
isHTMLSafe: (str: unknown) => str is SafeString;
Detects if a string was decorated using
htmlSafe
.```javascript import { htmlSafe, isHTMLSafe } from '@ember/template';
let plainString = 'plain string'; let safeString = htmlSafe('someValue');
isHTMLSafe(plainString); // false isHTMLSafe(safeString); // true ```
isHTMLSafe @ember/template {Boolean}
true
if the string was decorated withhtmlSafe
,false
otherwise.Modifiers
@public
class SafeString
class SafeString implements GlimmerSafeString {}
A wrapper around a string that has been marked as safe ("trusted"). **When rendered in HTML, Ember will not perform any escaping.**
Note:
1. This does not *make* the string safe; it means that some code in your application has *marked* it as safe using the
htmlSafe()
function.2. The only public API for getting a
SafeString
is callinghtmlSafe()
. It is *not* user-constructible.If a string contains user inputs or other untrusted data, you must sanitize the string before using the
htmlSafe
method. Otherwise your code is vulnerable to [Cross-Site Scripting][xss]. There are many open source sanitization libraries to choose from, both for front end and server-side sanitization.[xss]: https://owasp.org/www-community/attacks/DOM_Based_XSS
```javascript import { htmlSafe } from '@ember/template';
let someTrustedOrSanitizedString = "Hello!"
htmlSafe(someTrustedorSanitizedString); ```
@ember/template SafeString 4.12.0
Modifiers
@public
constructor
constructor(string: string);
method toHTML
toHTML: () => string;
Get the wrapped string as HTML to use without escaping.
toHTML
Returns
{String} the trusted string, without any escaping applied
Modifiers
@public
method toString
toString: () => string;
Get the string back to use as a string.
toString
Returns
{String} The string marked as trusted
Modifiers
@public
namespace @ember/template-compilation
module '@ember/template-compilation' {}
variable compileTemplate
const compileTemplate: ( templateString: string, options?: Partial<ETC.EmberPrecompileOptions>) => TemplateFactory;
variable precompileTemplate
let precompileTemplate: PrecompileTemplate;
namespace @ember/template-compiler
module '@ember/template-compiler' {}
function template
template: { ( templateString: string, options?: ExplicitTemplateOnlyOptions | ImplicitTemplateOnlyOptions ): TemplateOnlyComponent; <C extends ComponentClass>( templateString: string, options: | ExplicitClassOptions<C> | BaseClassTemplateOptions<C> | ImplicitClassOptions<C> ): C;};
interface EmberPrecompileOptions
interface EmberPrecompileOptions extends PrecompileOptions {}
property component
component?: object;
This supports template blocks defined in class bodies.
Manual form:
class MyComponent {static {template(templateContent, {component: this,eval: () => eval(arguments[0])})}}GJS form (compiled to the manual form via
content-tag
):class MyComponent {<template>Template Content</template>}
property eval
eval?: (value: string) => unknown;
property isProduction
isProduction?: boolean;
property lexicalScope
lexicalScope?: LexicalScope;
property moduleName
moduleName?: string;
property plugins
plugins?: Plugins;
property scope
scope?: () => Record<string, unknown>;
namespace @ember/template-compiler/-internal-primitives
module '@ember/template-compiler/-internal-primitives' {}
variable INTERNAL_PLUGINS
const INTERNAL_PLUGINS: { readonly AssertAgainstAttrs: typeof AssertAgainstAttrs; readonly AssertAgainstNamedOutlets: typeof AssertAgainstNamedOutlets; readonly AssertInputHelperWithoutBlock: typeof AssertInputHelperWithoutBlock; readonly AssertReservedNamedArguments: typeof AssertReservedNamedArguments; readonly TransformActionSyntax: typeof TransformActionSyntax; readonly TransformEachInIntoEach: typeof TransformEachInIntoEach; readonly TransformEachTrackArray: typeof TransformEachTrackArray; readonly TransformInElement: typeof TransformInElement; readonly TransformQuotedBindingsIntoJustBindings: typeof TransformQuotedBindingsIntoJustBindings; readonly TransformResolutions: typeof TransformResolutions; readonly TransformWrapMountAndOutlet: typeof TransformWrapMountAndOutlet;};
variable RESOLUTION_MODE_TRANSFORMS
const RESOLUTION_MODE_TRANSFORMS: readonly ((env: any) => ASTPlugin)[];
variable STRICT_MODE_KEYWORDS
const STRICT_MODE_KEYWORDS: readonly string[];
variable STRICT_MODE_TRANSFORMS
const STRICT_MODE_TRANSFORMS: readonly ((env: any) => ASTPlugin)[];
namespace @ember/template-compiler/-internal-utils
module '@ember/template-compiler/-internal-utils' {}
function inScope
inScope: (env: EmberASTPluginEnvironment, name: string) => boolean;
function isPath
isPath: (node: AST.Node) => node is AST.PathExpression;
function isStringLiteral
isStringLiteral: (node: AST.Expression) => node is AST.StringLiteral;
function trackLocals
trackLocals: (env: EmberASTPluginEnvironment) => { hasLocal: (key: string) => boolean; node: { enter(node: AST.Template | AST.Block | AST.ElementNode): void; exit(node: AST.Template | AST.Block | AST.ElementNode): void; }; visitor: { Template: { enter(node: AST.Template | AST.Block | AST.ElementNode): void; exit(node: AST.Template | AST.Block | AST.ElementNode): void; }; ElementNode: { enter(node: AST.Template | AST.Block | AST.ElementNode): void; exit(node: AST.Template | AST.Block | AST.ElementNode): void; }; Block: { enter(node: AST.Template | AST.Block | AST.ElementNode): void; exit(node: AST.Template | AST.Block | AST.ElementNode): void; }; };};
namespace @ember/template-compiler/lib/-internal/primitives
module '@ember/template-compiler/lib/-internal/primitives' {}
variable INTERNAL_PLUGINS
const INTERNAL_PLUGINS: { readonly AssertAgainstAttrs: typeof AssertAgainstAttrs; readonly AssertAgainstNamedOutlets: typeof AssertAgainstNamedOutlets; readonly AssertInputHelperWithoutBlock: typeof AssertInputHelperWithoutBlock; readonly AssertReservedNamedArguments: typeof AssertReservedNamedArguments; readonly TransformActionSyntax: typeof TransformActionSyntax; readonly TransformEachInIntoEach: typeof TransformEachInIntoEach; readonly TransformEachTrackArray: typeof TransformEachTrackArray; readonly TransformInElement: typeof TransformInElement; readonly TransformQuotedBindingsIntoJustBindings: typeof TransformQuotedBindingsIntoJustBindings; readonly TransformResolutions: typeof TransformResolutions; readonly TransformWrapMountAndOutlet: typeof TransformWrapMountAndOutlet;};
variable RESOLUTION_MODE_TRANSFORMS
const RESOLUTION_MODE_TRANSFORMS: readonly ((env: any) => ASTPlugin)[];
variable STRICT_MODE_KEYWORDS
const STRICT_MODE_KEYWORDS: readonly string[];
variable STRICT_MODE_TRANSFORMS
const STRICT_MODE_TRANSFORMS: readonly ((env: any) => ASTPlugin)[];
namespace @ember/template-compiler/lib/compile-options
module '@ember/template-compiler/lib/compile-options' {}
function compileOptions
compileOptions: ( _options?: Partial<EmberPrecompileOptions>) => EmberPrecompileOptions;
namespace @ember/template-compiler/lib/dasherize-component-name
module '@ember/template-compiler/lib/dasherize-component-name' {}
variable _default
const _default: Cache<string, string>;
namespace @ember/template-compiler/lib/plugins
module '@ember/template-compiler/lib/plugins' {}
variable INTERNAL_PLUGINS
const INTERNAL_PLUGINS: { readonly AssertAgainstAttrs: typeof AssertAgainstAttrs; readonly AssertAgainstNamedOutlets: typeof AssertAgainstNamedOutlets; readonly AssertInputHelperWithoutBlock: typeof AssertInputHelperWithoutBlock; readonly AssertReservedNamedArguments: typeof AssertReservedNamedArguments; readonly TransformActionSyntax: typeof TransformActionSyntax; readonly TransformEachInIntoEach: typeof TransformEachInIntoEach; readonly TransformEachTrackArray: typeof TransformEachTrackArray; readonly TransformInElement: typeof TransformInElement; readonly TransformQuotedBindingsIntoJustBindings: typeof TransformQuotedBindingsIntoJustBindings; readonly TransformResolutions: typeof TransformResolutions; readonly TransformWrapMountAndOutlet: typeof TransformWrapMountAndOutlet;};
variable RESOLUTION_MODE_TRANSFORMS
const RESOLUTION_MODE_TRANSFORMS: readonly ((env: any) => ASTPlugin)[];
variable STRICT_MODE_KEYWORDS
const STRICT_MODE_KEYWORDS: readonly string[];
variable STRICT_MODE_TRANSFORMS
const STRICT_MODE_TRANSFORMS: readonly ((env: any) => ASTPlugin)[];
namespace @ember/template-compiler/lib/plugins/assert-against-attrs
module '@ember/template-compiler/lib/plugins/assert-against-attrs' {}
function assertAgainstAttrs
assertAgainstAttrs: (env: EmberASTPluginEnvironment) => ASTPlugin;
A Glimmer2 AST transformation that asserts against
```handlebars {{attrs.foo.bar}} ```
...as well as
{{#if attrs.foo}}
,{{deeply (nested attrs.foobar.baz)}}
.AssertAgainstAttrs
namespace @ember/template-compiler/lib/plugins/assert-against-named-outlets
module '@ember/template-compiler/lib/plugins/assert-against-named-outlets' {}
function assertAgainstNamedOutlets
assertAgainstNamedOutlets: (env: EmberASTPluginEnvironment) => ASTPlugin;
Prevents usage of named outlets, a legacy concept in Ember removed in 4.0.
AssertAgainstNamedOutlets
namespace @ember/template-compiler/lib/plugins/assert-input-helper-without-block
module '@ember/template-compiler/lib/plugins/assert-input-helper-without-block' {}
function errorOnInputWithContent
errorOnInputWithContent: (env: EmberASTPluginEnvironment) => ASTPlugin;
namespace @ember/template-compiler/lib/plugins/assert-reserved-named-arguments
module '@ember/template-compiler/lib/plugins/assert-reserved-named-arguments' {}
function assertReservedNamedArguments
assertReservedNamedArguments: (env: EmberASTPluginEnvironment) => ASTPlugin;
namespace @ember/template-compiler/lib/plugins/transform-action-syntax
module '@ember/template-compiler/lib/plugins/transform-action-syntax' {}
function transformActionSyntax
transformActionSyntax: (env: EmberASTPluginEnvironment) => ASTPlugin;
A Glimmer2 AST transformation that replaces all instances of
```handlebars <button {{action 'foo'}}> <button onblur={{action 'foo'}}> <button onblur={{action (action 'foo') 'bar'}}> ```
with
```handlebars <button {{action this 'foo'}}> <button onblur={{action this 'foo'}}> <button onblur={{action this (action this 'foo') 'bar'}}> ```
TransformActionSyntax
namespace @ember/template-compiler/lib/plugins/transform-each-in-into-each
module '@ember/template-compiler/lib/plugins/transform-each-in-into-each' {}
function transformEachInIntoEach
transformEachInIntoEach: (env: EmberASTPluginEnvironment) => ASTPlugin;
A Glimmer2 AST transformation that replaces all instances of
```handlebars {{#each-in iterableThing as |key value|}} ```
with
```handlebars {{#each (-each-in iterableThing) as |value key|}} ```
TransformHasBlockSyntax
namespace @ember/template-compiler/lib/plugins/transform-each-track-array
module '@ember/template-compiler/lib/plugins/transform-each-track-array' {}
function transformEachTrackArray
transformEachTrackArray: (env: EmberASTPluginEnvironment) => ASTPlugin;
A Glimmer2 AST transformation that replaces all instances of
```handlebars {{#each iterableThing as |key value|}} ```
with
```handlebars {{#each (-track-array iterableThing) as |key value|}} ```
TransformHasBlockSyntax
namespace @ember/template-compiler/lib/plugins/transform-in-element
module '@ember/template-compiler/lib/plugins/transform-in-element' {}
function transformInElement
transformInElement: (env: EmberASTPluginEnvironment) => ASTPlugin;
A Glimmer2 AST transformation that handles the public
{{in-element}}
as per RFC287.Issues a build time assertion for:
```handlebars {{#in-element someElement insertBefore="some-none-null-value"}} {{modal-display text=text}} {{/in-element}} ```
TransformInElement
namespace @ember/template-compiler/lib/plugins/transform-quoted-bindings-into-just-bindings
module '@ember/template-compiler/lib/plugins/transform-quoted-bindings-into-just-bindings' {}
function transformQuotedBindingsIntoJustBindings
transformQuotedBindingsIntoJustBindings: () => ASTPlugin;
namespace @ember/template-compiler/lib/plugins/transform-resolutions
module '@ember/template-compiler/lib/plugins/transform-resolutions' {}
function transformResolutions
transformResolutions: (env: EmberASTPluginEnvironment) => ASTPlugin;
namespace @ember/template-compiler/lib/plugins/transform-wrap-mount-and-outlet
module '@ember/template-compiler/lib/plugins/transform-wrap-mount-and-outlet' {}
function transformWrapMountAndOutlet
transformWrapMountAndOutlet: (env: EmberASTPluginEnvironment) => ASTPlugin;
A Glimmer2 AST transformation that replaces all instances of
```handlebars {{mount "engine" model=this.model}} ```
with
```handlebars {{component (-mount "engine" model=this.model)}} ```
and
```handlebars {{outlet}} ```
with
```handlebars {{component (-outlet)}} ```
TransformHasBlockSyntax
namespace @ember/template-compiler/lib/plugins/utils
module '@ember/template-compiler/lib/plugins/utils' {}
function inScope
inScope: (env: EmberASTPluginEnvironment, name: string) => boolean;
function isPath
isPath: (node: AST.Node) => node is AST.PathExpression;
function isStringLiteral
isStringLiteral: (node: AST.Expression) => node is AST.StringLiteral;
function trackLocals
trackLocals: (env: EmberASTPluginEnvironment) => { hasLocal: (key: string) => boolean; node: { enter(node: AST.Template | AST.Block | AST.ElementNode): void; exit(node: AST.Template | AST.Block | AST.ElementNode): void; }; visitor: { Template: { enter(node: AST.Template | AST.Block | AST.ElementNode): void; exit(node: AST.Template | AST.Block | AST.ElementNode): void; }; ElementNode: { enter(node: AST.Template | AST.Block | AST.ElementNode): void; exit(node: AST.Template | AST.Block | AST.ElementNode): void; }; Block: { enter(node: AST.Template | AST.Block | AST.ElementNode): void; exit(node: AST.Template | AST.Block | AST.ElementNode): void; }; };};
namespace @ember/template-compiler/lib/public-api
module '@ember/template-compiler/lib/public-api' {}
function template
template: { ( templateString: string, options?: ExplicitTemplateOnlyOptions | ImplicitTemplateOnlyOptions ): TemplateOnlyComponent; <C extends ComponentClass>( templateString: string, options: | ExplicitClassOptions<C> | BaseClassTemplateOptions<C> | ImplicitClassOptions<C> ): C;};
interface EmberPrecompileOptions
interface EmberPrecompileOptions extends PrecompileOptions {}
property component
component?: object;
This supports template blocks defined in class bodies.
Manual form:
class MyComponent {static {template(templateContent, {component: this,eval: () => eval(arguments[0])})}}GJS form (compiled to the manual form via
content-tag
):class MyComponent {<template>Template Content</template>}
property eval
eval?: (value: string) => unknown;
property isProduction
isProduction?: boolean;
property lexicalScope
lexicalScope?: LexicalScope;
property moduleName
moduleName?: string;
property plugins
plugins?: Plugins;
property scope
scope?: () => Record<string, unknown>;
namespace @ember/template-compiler/lib/public-types
module '@ember/template-compiler/lib/public-types' {}
interface BaseClassTemplateOptions
interface BaseClassTemplateOptions<C extends ComponentClass> extends BaseTemplateOptions {}
When using
template
in a class, you call it in astatic
block and pass the class as thecomponent
option.class MyComponent extends Component {static {template('{{this.greeting}}, {{@place}}!',{ component: this },// explicit or implicit option goes here);}}For the full explicit form, see . For the full implicit form, see .
property component
component: C;
interface BaseTemplateOptions
interface BaseTemplateOptions {}
All possible options passed to
template()
may specify amoduleName
.
property moduleName
moduleName?: string;
property strictMode
strictMode?: boolean;
Whether the template should be treated as a strict-mode template. Defaults to
true
.
interface ExplicitClassOptions
interface ExplicitClassOptions<C extends ComponentClass> extends BaseClassTemplateOptions<C> {}
When using
template
*inside* a class (see ), you can pass ascope
option that explicitly provides the lexical scope for the template, just like a template-only component (see ).class MyComponent extends Component {static {template('{{this.greeting}}, {{@place}}!',{ component: this },// explicit or implicit option goes here);}}## The Scope Function's
instance
ParameterHowever, the explicit
scope
function in a *class* also takes aninstance
option that provides access to the component's instance.Once it's supported in Handlebars, this will make it possible to represent private fields when using the explicit form.
class MyComponent extends Component {static {template('{{this.#greeting}}, {{@place}}!',{ component: this },scope: (instance) => ({ '#greeting': instance.#greeting }),);}}
method scope
scope: (instance?: InstanceType<C>) => Record<string, unknown>;
interface ExplicitTemplateOnlyOptions
interface ExplicitTemplateOnlyOptions extends BaseTemplateOptions {}
When using
template
outside of a class (i.e. a "template-only component"), you can pass ascope
option that explicitly provides the lexical scope for the template.This is called the "explicit form".
const greeting = 'Hello';const HelloWorld = template('{{greeting}} World!', { scope: () => ({ greeting }) });
method scope
scope: () => Record<string, unknown>;
interface ImplicitEvalOption
interface ImplicitEvalOption {}
The *implicit* form of the
template
function takes aneval
option that allows the runtime compiler to evaluate local template variables without needing to maintain an explicit list of the local variables used in the template scope.The eval options *must* be passed in the following form:
{eval() { return eval(arguments[0]) }}## Requirements of the
eval
Option**The syntactic form presented above is the only form you should use when passing an
eval
option.**This is _required_ if you want your code to be compatible with the compile-time implementation of
@ember/template-compiler
. While the runtime compiler offers a tiny bit of additional wiggle room, you still need to follow very strict rules.We don't recommend trying to memorize the rules. Instead, we recommend using the snippet presented above and supported by the compile-time implementation.
### The Technical Requirements of the
eval
OptionThe
eval
function is passed a single parameter that is a JavaScript identifier. This will be extended in the future to support private fields.Since keywords in JavaScript are contextual (e.g.
await
andyield
), the parameter might be a keyword. The@ember/template-compiler/runtime
expects the function to throw aSyntaxError
if the identifier name is not valid in the current scope. (The directeval
function takes care of this out of the box.)Requirements:
1. The
eval
method must receive its parameter asarguments[0]
, which ensures that the variable name passed toeval()
is not shadowed by the function's parameter name. 2. Theeval
option must be a function or concise method, and not an arrow. This is because arrows do not have their ownarguments
, which breaks (1). 3. Theeval
method must call "*direct*eval
", and not an alias ofeval
. Directeval
evaluates the code in the scope it was called from, while aliased versions ofeval
(includingnew Function
) evaluate the code in the global scope. 4. Theeval
method must return the result of calling "directeval
".The easiest way to achieve these requirements is to use the exact syntax presented above. This is *also* the only way to be compatible
## Rationale
This is useful for two reasons:
1. This form is a useful _intermediate_ form for the compile-time toolchain. It allows the content-tag preprocessor to convert the
<template>
syntax into valid JavaScript without needing to involve full-fledged lexical analysis. 2. This form is a convenient form for manual prototyping when using the runtime compiler directly. While it requires some extra typing relative to<template>
, it's a mechanical 1:1 transformation of the syntax.In practice, implementations that use a runtime compiler (for example, a playground running completely in the browser) should probably use the
content-tag
preprocessor to convert the template into the implicit form, and then rely on@ember/template-compiler/runtime
to evaluate the template.
method eval
eval: () => unknown;
type ImplicitClassOptions
type ImplicitClassOptions<C extends ComponentClass> = BaseClassTemplateOptions<C> & ImplicitEvalOption;
When using
template
inside of a class, you can pass aneval
option that _implicitly_ provides the lexical scope for the template, just as you can with a .This is called the "implicit form".
class MyComponent extends Component {static {template('{{this.greeting}}, {{@place}}!',{ component: this },eval() { return arguments[0] });}}## Note on Private Fields
The current implementation of
@ember/template-compiler
does not support private fields, but once the Handlebars parser adds support for private field syntax and it's implemented in the Glimmer compiler, the implicit form should be able to support them.
type ImplicitTemplateOnlyOptions
type ImplicitTemplateOnlyOptions = BaseTemplateOptions & ImplicitEvalOption;
When using
template
outside of a class (i.e. a "template-only component"), you can pass aneval
option that _implicitly_ provides the lexical scope for the template.This is called the "implicit form".
const greeting = 'Hello';const HelloWorld = template('{{greeting}} World!', {eval() { return arguments[0] }});For more details on the requirements of the
eval
option, see .
namespace @ember/template-compiler/lib/runtime
module '@ember/template-compiler/lib/runtime' {}
function template
template: { ( templateString: string, options?: ExplicitTemplateOnlyOptions | ImplicitTemplateOnlyOptions ): TemplateOnlyComponent; <C extends ComponentClass>( templateString: string, options: | ExplicitClassOptions<C> | BaseClassTemplateOptions<C> | ImplicitClassOptions<C> ): C;};
interface EmberPrecompileOptions
interface EmberPrecompileOptions extends PrecompileOptions {}
property component
component?: object;
This supports template blocks defined in class bodies.
Manual form:
class MyComponent {static {template(templateContent, {component: this,eval: () => eval(arguments[0])})}}GJS form (compiled to the manual form via
content-tag
):class MyComponent {<template>Template Content</template>}
property eval
eval?: (value: string) => unknown;
property isProduction
isProduction?: boolean;
property lexicalScope
lexicalScope?: LexicalScope;
property moduleName
moduleName?: string;
property plugins
plugins?: Plugins;
property scope
scope?: () => Record<string, unknown>;
namespace @ember/template-compiler/lib/system/calculate-location-display
module '@ember/template-compiler/lib/system/calculate-location-display' {}
function calculateLocationDisplay
calculateLocationDisplay: ( moduleName: string | undefined, loc?: AST.SourceLocation | undefined) => string;
namespace @ember/template-compiler/lib/template
module '@ember/template-compiler/lib/template' {}
function template
template: { ( templateString: string, options?: ExplicitTemplateOnlyOptions | ImplicitTemplateOnlyOptions ): TemplateOnlyComponent; <C extends ComponentClass>( templateString: string, options: | ExplicitClassOptions<C> | BaseClassTemplateOptions<C> | ImplicitClassOptions<C> ): C;};
interface BaseClassTemplateOptions
interface BaseClassTemplateOptions<C extends ComponentClass> extends BaseTemplateOptions {}
When using
template
in a class, you call it in astatic
block and pass the class as thecomponent
option.class MyComponent extends Component {static {template('{{this.greeting}}, {{@place}}!',{ component: this },// explicit or implicit option goes here);}}For the full explicit form, see . For the full implicit form, see .
property component
component: C;
interface BaseTemplateOptions
interface BaseTemplateOptions {}
All possible options passed to
template()
may specify amoduleName
.
property moduleName
moduleName?: string;
property strictMode
strictMode?: boolean;
Whether the template should be treated as a strict-mode template. Defaults to
true
.
interface ExplicitClassOptions
interface ExplicitClassOptions<C extends ComponentClass> extends BaseClassTemplateOptions<C> {}
When using
template
*inside* a class (see ), you can pass ascope
option that explicitly provides the lexical scope for the template, just like a template-only component (see ).class MyComponent extends Component {static {template('{{this.greeting}}, {{@place}}!',{ component: this },// explicit or implicit option goes here);}}## The Scope Function's
instance
ParameterHowever, the explicit
scope
function in a *class* also takes aninstance
option that provides access to the component's instance.Once it's supported in Handlebars, this will make it possible to represent private fields when using the explicit form.
class MyComponent extends Component {static {template('{{this.#greeting}}, {{@place}}!',{ component: this },scope: (instance) => ({ '#greeting': instance.#greeting }),);}}
method scope
scope: (instance?: InstanceType<C>) => Record<string, unknown>;
interface ExplicitTemplateOnlyOptions
interface ExplicitTemplateOnlyOptions extends BaseTemplateOptions {}
When using
template
outside of a class (i.e. a "template-only component"), you can pass ascope
option that explicitly provides the lexical scope for the template.This is called the "explicit form".
const greeting = 'Hello';const HelloWorld = template('{{greeting}} World!', { scope: () => ({ greeting }) });
method scope
scope: () => Record<string, unknown>;
interface ImplicitEvalOption
interface ImplicitEvalOption {}
The *implicit* form of the
template
function takes aneval
option that allows the runtime compiler to evaluate local template variables without needing to maintain an explicit list of the local variables used in the template scope.The eval options *must* be passed in the following form:
{eval() { return eval(arguments[0]) }}## Requirements of the
eval
Option**The syntactic form presented above is the only form you should use when passing an
eval
option.**This is _required_ if you want your code to be compatible with the compile-time implementation of
@ember/template-compiler
. While the runtime compiler offers a tiny bit of additional wiggle room, you still need to follow very strict rules.We don't recommend trying to memorize the rules. Instead, we recommend using the snippet presented above and supported by the compile-time implementation.
### The Technical Requirements of the
eval
OptionThe
eval
function is passed a single parameter that is a JavaScript identifier. This will be extended in the future to support private fields.Since keywords in JavaScript are contextual (e.g.
await
andyield
), the parameter might be a keyword. The@ember/template-compiler/runtime
expects the function to throw aSyntaxError
if the identifier name is not valid in the current scope. (The directeval
function takes care of this out of the box.)Requirements:
1. The
eval
method must receive its parameter asarguments[0]
, which ensures that the variable name passed toeval()
is not shadowed by the function's parameter name. 2. Theeval
option must be a function or concise method, and not an arrow. This is because arrows do not have their ownarguments
, which breaks (1). 3. Theeval
method must call "*direct*eval
", and not an alias ofeval
. Directeval
evaluates the code in the scope it was called from, while aliased versions ofeval
(includingnew Function
) evaluate the code in the global scope. 4. Theeval
method must return the result of calling "directeval
".The easiest way to achieve these requirements is to use the exact syntax presented above. This is *also* the only way to be compatible
## Rationale
This is useful for two reasons:
1. This form is a useful _intermediate_ form for the compile-time toolchain. It allows the content-tag preprocessor to convert the
<template>
syntax into valid JavaScript without needing to involve full-fledged lexical analysis. 2. This form is a convenient form for manual prototyping when using the runtime compiler directly. While it requires some extra typing relative to<template>
, it's a mechanical 1:1 transformation of the syntax.In practice, implementations that use a runtime compiler (for example, a playground running completely in the browser) should probably use the
content-tag
preprocessor to convert the template into the implicit form, and then rely on@ember/template-compiler/runtime
to evaluate the template.
method eval
eval: () => unknown;
type ImplicitClassOptions
type ImplicitClassOptions<C extends ComponentClass> = BaseClassTemplateOptions<C> & ImplicitEvalOption;
When using
template
inside of a class, you can pass aneval
option that _implicitly_ provides the lexical scope for the template, just as you can with a .This is called the "implicit form".
class MyComponent extends Component {static {template('{{this.greeting}}, {{@place}}!',{ component: this },eval() { return arguments[0] });}}## Note on Private Fields
The current implementation of
@ember/template-compiler
does not support private fields, but once the Handlebars parser adds support for private field syntax and it's implemented in the Glimmer compiler, the implicit form should be able to support them.
type ImplicitTemplateOnlyOptions
type ImplicitTemplateOnlyOptions = BaseTemplateOptions & ImplicitEvalOption;
When using
template
outside of a class (i.e. a "template-only component"), you can pass aneval
option that _implicitly_ provides the lexical scope for the template.This is called the "implicit form".
const greeting = 'Hello';const HelloWorld = template('{{greeting}} World!', {eval() { return arguments[0] }});For more details on the requirements of the
eval
option, see .
namespace @ember/template-compiler/lib/types
module '@ember/template-compiler/lib/types' {}
interface EmberPrecompileOptions
interface EmberPrecompileOptions extends PrecompileOptions {}
property component
component?: object;
This supports template blocks defined in class bodies.
Manual form:
class MyComponent {static {template(templateContent, {component: this,eval: () => eval(arguments[0])})}}GJS form (compiled to the manual form via
content-tag
):class MyComponent {<template>Template Content</template>}
property eval
eval?: (value: string) => unknown;
property isProduction
isProduction?: boolean;
property lexicalScope
lexicalScope?: LexicalScope;
property moduleName
moduleName?: string;
property plugins
plugins?: Plugins;
property scope
scope?: () => Record<string, unknown>;
type Builders
type Builders = typeof builders;
type EmberASTPluginEnvironment
type EmberASTPluginEnvironment = ASTPluginEnvironment & EmberPrecompileOptions;
type LexicalScope
type LexicalScope = NonNullable<PrecompileOptionsWithLexicalScope['lexicalScope']>;
type PluginFunc
type PluginFunc = NonNullable< NonNullable<PrecompileOptionsWithLexicalScope['plugins']>['ast']>[number];
namespace @ember/template-compiler/runtime
module '@ember/template-compiler/runtime' {}
function template
template: { ( templateString: string, options?: ExplicitTemplateOnlyOptions | ImplicitTemplateOnlyOptions ): TemplateOnlyComponent; <C extends ComponentClass>( templateString: string, options: | ExplicitClassOptions<C> | BaseClassTemplateOptions<C> | ImplicitClassOptions<C> ): C;};
interface EmberPrecompileOptions
interface EmberPrecompileOptions extends PrecompileOptions {}
property component
component?: object;
This supports template blocks defined in class bodies.
Manual form:
class MyComponent {static {template(templateContent, {component: this,eval: () => eval(arguments[0])})}}GJS form (compiled to the manual form via
content-tag
):class MyComponent {<template>Template Content</template>}
property eval
eval?: (value: string) => unknown;
property isProduction
isProduction?: boolean;
property lexicalScope
lexicalScope?: LexicalScope;
property moduleName
moduleName?: string;
property plugins
plugins?: Plugins;
property scope
scope?: () => Record<string, unknown>;
namespace @ember/template-factory
module '@ember/template-factory' {}
namespace @ember/test
module '@ember/test' {}
variable registerAsyncHelper
let registerAsyncHelper: (name: string, helperMethod: AnyFn) => void;
variable registerHelper
let registerHelper: ( name: string, helperMethod: (app: Application, ...args: any[]) => unknown) => void;
variable registerWaiter
let registerWaiter: { <T>(context: T, callback: (this: T) => unknown): void; (callback: (this: null) => unknown): void;};
variable unregisterHelper
let unregisterHelper: (name: string) => void;
variable unregisterWaiter
let unregisterWaiter: (context: unknown, callback: unknown) => void;
function registerTestImplementation
registerTestImplementation: (impl: typeof EmberTesting) => void;
namespace @ember/test/adapter
module '@ember/test/adapter' {}
variable Adapter
const Adapter: Readonly<typeof EmberObject> & (new (owner?: import('@ember/owner').default | undefined) => EmberObject) & { asyncStart(): void; asyncEnd(): void; exception(error: unknown): never; };
interface Adapter
interface Adapter extends EmberObject {}
The primary purpose of this class is to create hooks that can be implemented by an adapter for various test frameworks.
TestAdapter
Modifiers
@public
method asyncEnd
asyncEnd: () => void;
method asyncStart
asyncStart: () => void;
method exception
exception: (error: unknown) => never;
namespace @ember/utils
module '@ember/utils' {}
function compare
compare: <T>(v: T, w: T) => Compare;
Compares two javascript values and returns:
- -1 if the first is smaller than the second, - 0 if both are equal, - 1 if the first is greater than the second.
```javascript import { compare } from '@ember/utils';
compare('hello', 'hello'); // 0 compare('abc', 'dfg'); // -1 compare(2, 1); // 1 ```
If the types of the two objects are different precedence occurs in the following order, with types earlier in the list considered
<
types later in the list:- undefined - null - boolean - number - string - array - object - instance - function - class - date
```javascript import { compare } from '@ember/utils';
compare('hello', 50); // 1 compare(50, 'hello'); // -1 ```
compare @ember/utils
Parameter v
First value to compare
Parameter w
Second value to compare {Number} -1 if v < w, 0 if v = w and 1 if v > w.
Modifiers
@public
function isBlank
isBlank: (obj: unknown) => boolean;
A value is blank if it is empty or a whitespace string.
```javascript import { isBlank } from '@ember/utils';
isBlank(null); // true isBlank(undefined); // true isBlank(''); // true isBlank([]); // true isBlank('\n\t'); // true isBlank(' '); // true isBlank({}); // false isBlank('\n\t Hello'); // false isBlank('Hello world'); // false isBlank([1,2,3]); // false ```
isBlank @ember/utils
Parameter obj
Value to test {Boolean} 1.5.0
Modifiers
@public
function isEmpty
isEmpty: (obj: unknown) => boolean;
Verifies that a value is
null
orundefined
, an empty string, or an empty array.Constrains the rules on
isNone
by returning true for empty strings and empty arrays.If the value is an object with a
size
property of type number, it is used to check emptiness.```javascript isEmpty(null); // true isEmpty(undefined); // true isEmpty(''); // true isEmpty([]); // true isEmpty({ size: 0}); // true isEmpty({}); // false isEmpty('Adam Hawkins'); // false isEmpty([0,1,2]); // false isEmpty('\n\t'); // false isEmpty(' '); // false isEmpty({ size: 1 }) // false isEmpty({ size: () => 0 }) // false ```
isEmpty @ember/utils
Parameter obj
Value to test {Boolean}
Modifiers
@public
function isEqual
isEqual: (a: unknown, b: unknown) => boolean;
Compares two objects, returning true if they are equal.
```javascript import { isEqual } from '@ember/utils';
isEqual('hello', 'hello'); // true isEqual(1, 2); // false ```
isEqual
is a more specific comparison than a triple equal comparison. It will call theisEqual
instance method on the objects being compared, allowing finer control over when objects should be considered equal to each other.```javascript import { isEqual } from '@ember/utils'; import EmberObject from '@ember/object';
let Person = EmberObject.extend({ isEqual(other) { return this.ssn == other.ssn; } });
let personA = Person.create({name: 'Muhammad Ali', ssn: '123-45-6789'}); let personB = Person.create({name: 'Cassius Clay', ssn: '123-45-6789'});
isEqual(personA, personB); // true ```
Due to the expense of array comparisons, collections will never be equal to each other even if each of their items are equal to each other.
```javascript import { isEqual } from '@ember/utils';
isEqual([4, 2], [4, 2]); // false ```
isEqual @ember/utils
Parameter a
first object to compare
Parameter b
second object to compare {Boolean}
Modifiers
@public
function isNone
isNone: (obj: any) => obj is null;
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 isNone(null); // true isNone(undefined); // true isNone(''); // false isNone([]); // false isNone(function() {}); // false ```
isNone @ember/utils
Parameter obj
Value to test {Boolean}
Modifiers
@public
function isPresent
isPresent: <T>(obj: T | null | undefined) => obj is T;
A value is present if it not
isBlank
.```javascript isPresent(null); // false isPresent(undefined); // false isPresent(''); // false isPresent(' '); // false isPresent('\n\t'); // false isPresent([]); // false isPresent({ length: 0 }); // false isPresent(false); // true isPresent(true); // true isPresent('string'); // true isPresent(0); // true isPresent(function() {}); // true isPresent({}); // true isPresent('\n\t Hello'); // true isPresent([1, 2, 3]); // true ```
isPresent @ember/utils
Parameter obj
Value to test {Boolean} 1.8.0
Modifiers
@public
function typeOf
typeOf: (item: unknown) => TypeName;
Returns a consistent type for the passed object.
Use this instead of the built-in
typeof
to get the type of an item. It will return the same result across all browsers and includes a bit more detail. Here is what will be returned:| Return Value | Meaning | |---------------|------------------------------------------------------| | 'string' | String primitive or String object. | | 'number' | Number primitive or Number object. | | 'boolean' | Boolean primitive or Boolean object. | | 'null' | Null value | | 'undefined' | Undefined value | | 'function' | A function | | 'array' | An instance of Array | | 'regexp' | An instance of RegExp | | 'date' | An instance of Date | | 'filelist' | An instance of FileList | | 'class' | An Ember class (created using EmberObject.extend()) | | 'instance' | An Ember object instance | | 'error' | An instance of the Error object | | 'object' | A JavaScript object not inheriting from EmberObject |
Examples:
```javascript import { A } from '@ember/array'; import { typeOf } from '@ember/utils'; import EmberObject from '@ember/object';
typeOf(); // 'undefined' typeOf(null); // 'null' typeOf(undefined); // 'undefined' typeOf('michael'); // 'string' typeOf(new String('michael')); // 'string' typeOf(101); // 'number' typeOf(new Number(101)); // 'number' typeOf(true); // 'boolean' typeOf(new Boolean(true)); // 'boolean' typeOf(A); // 'function' typeOf(A()); // 'array' typeOf([1, 2, 90]); // 'array' typeOf(/abc/); // 'regexp' typeOf(new Date()); // 'date' typeOf(event.target.files); // 'filelist' typeOf(EmberObject.extend()); // 'class' typeOf(EmberObject.create()); // 'instance' typeOf(new Error('teamocil')); // 'error'
// 'normal' JavaScript object typeOf({ a: 'b' }); // 'object' ```
typeOf @ember/utils
Parameter item
the item to check {String} the type
Modifiers
@public
namespace @ember/utils/lib/compare
module '@ember/utils/lib/compare' {}
function compare
compare: <T>(v: T, w: T) => Compare;
Compares two javascript values and returns:
- -1 if the first is smaller than the second, - 0 if both are equal, - 1 if the first is greater than the second.
```javascript import { compare } from '@ember/utils';
compare('hello', 'hello'); // 0 compare('abc', 'dfg'); // -1 compare(2, 1); // 1 ```
If the types of the two objects are different precedence occurs in the following order, with types earlier in the list considered
<
types later in the list:- undefined - null - boolean - number - string - array - object - instance - function - class - date
```javascript import { compare } from '@ember/utils';
compare('hello', 50); // 1 compare(50, 'hello'); // -1 ```
compare @ember/utils
Parameter v
First value to compare
Parameter w
Second value to compare {Number} -1 if v < w, 0 if v = w and 1 if v > w.
Modifiers
@public
namespace @ember/utils/lib/is_blank
module '@ember/utils/lib/is_blank' {}
function isBlank
isBlank: (obj: unknown) => boolean;
A value is blank if it is empty or a whitespace string.
```javascript import { isBlank } from '@ember/utils';
isBlank(null); // true isBlank(undefined); // true isBlank(''); // true isBlank([]); // true isBlank('\n\t'); // true isBlank(' '); // true isBlank({}); // false isBlank('\n\t Hello'); // false isBlank('Hello world'); // false isBlank([1,2,3]); // false ```
isBlank @ember/utils
Parameter obj
Value to test {Boolean} 1.5.0
Modifiers
@public
namespace @ember/utils/lib/is_empty
module '@ember/utils/lib/is_empty' {}
function isEmpty
isEmpty: (obj: unknown) => boolean;
Verifies that a value is
null
orundefined
, an empty string, or an empty array.Constrains the rules on
isNone
by returning true for empty strings and empty arrays.If the value is an object with a
size
property of type number, it is used to check emptiness.```javascript isEmpty(null); // true isEmpty(undefined); // true isEmpty(''); // true isEmpty([]); // true isEmpty({ size: 0}); // true isEmpty({}); // false isEmpty('Adam Hawkins'); // false isEmpty([0,1,2]); // false isEmpty('\n\t'); // false isEmpty(' '); // false isEmpty({ size: 1 }) // false isEmpty({ size: () => 0 }) // false ```
isEmpty @ember/utils
Parameter obj
Value to test {Boolean}
Modifiers
@public
namespace @ember/utils/lib/is_none
module '@ember/utils/lib/is_none' {}
function isNone
isNone: (obj: any) => obj is null;
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 isNone(null); // true isNone(undefined); // true isNone(''); // false isNone([]); // false isNone(function() {}); // false ```
isNone @ember/utils
Parameter obj
Value to test {Boolean}
Modifiers
@public
namespace @ember/utils/lib/is_present
module '@ember/utils/lib/is_present' {}
function isPresent
isPresent: <T>(obj: T | null | undefined) => obj is T;
A value is present if it not
isBlank
.```javascript isPresent(null); // false isPresent(undefined); // false isPresent(''); // false isPresent(' '); // false isPresent('\n\t'); // false isPresent([]); // false isPresent({ length: 0 }); // false isPresent(false); // true isPresent(true); // true isPresent('string'); // true isPresent(0); // true isPresent(function() {}); // true isPresent({}); // true isPresent('\n\t Hello'); // true isPresent([1, 2, 3]); // true ```
isPresent @ember/utils
Parameter obj
Value to test {Boolean} 1.8.0
Modifiers
@public
namespace @ember/utils/lib/is-equal
module '@ember/utils/lib/is-equal' {}
function isEqual
isEqual: (a: unknown, b: unknown) => boolean;
Compares two objects, returning true if they are equal.
```javascript import { isEqual } from '@ember/utils';
isEqual('hello', 'hello'); // true isEqual(1, 2); // false ```
isEqual
is a more specific comparison than a triple equal comparison. It will call theisEqual
instance method on the objects being compared, allowing finer control over when objects should be considered equal to each other.```javascript import { isEqual } from '@ember/utils'; import EmberObject from '@ember/object';
let Person = EmberObject.extend({ isEqual(other) { return this.ssn == other.ssn; } });
let personA = Person.create({name: 'Muhammad Ali', ssn: '123-45-6789'}); let personB = Person.create({name: 'Cassius Clay', ssn: '123-45-6789'});
isEqual(personA, personB); // true ```
Due to the expense of array comparisons, collections will never be equal to each other even if each of their items are equal to each other.
```javascript import { isEqual } from '@ember/utils';
isEqual([4, 2], [4, 2]); // false ```
isEqual @ember/utils
Parameter a
first object to compare
Parameter b
second object to compare {Boolean}
Modifiers
@public
namespace @ember/utils/lib/type-of
module '@ember/utils/lib/type-of' {}
function typeOf
typeOf: (item: unknown) => TypeName;
Returns a consistent type for the passed object.
Use this instead of the built-in
typeof
to get the type of an item. It will return the same result across all browsers and includes a bit more detail. Here is what will be returned:| Return Value | Meaning | |---------------|------------------------------------------------------| | 'string' | String primitive or String object. | | 'number' | Number primitive or Number object. | | 'boolean' | Boolean primitive or Boolean object. | | 'null' | Null value | | 'undefined' | Undefined value | | 'function' | A function | | 'array' | An instance of Array | | 'regexp' | An instance of RegExp | | 'date' | An instance of Date | | 'filelist' | An instance of FileList | | 'class' | An Ember class (created using EmberObject.extend()) | | 'instance' | An Ember object instance | | 'error' | An instance of the Error object | | 'object' | A JavaScript object not inheriting from EmberObject |
Examples:
```javascript import { A } from '@ember/array'; import { typeOf } from '@ember/utils'; import EmberObject from '@ember/object';
typeOf(); // 'undefined' typeOf(null); // 'null' typeOf(undefined); // 'undefined' typeOf('michael'); // 'string' typeOf(new String('michael')); // 'string' typeOf(101); // 'number' typeOf(new Number(101)); // 'number' typeOf(true); // 'boolean' typeOf(new Boolean(true)); // 'boolean' typeOf(A); // 'function' typeOf(A()); // 'array' typeOf([1, 2, 90]); // 'array' typeOf(/abc/); // 'regexp' typeOf(new Date()); // 'date' typeOf(event.target.files); // 'filelist' typeOf(EmberObject.extend()); // 'class' typeOf(EmberObject.create()); // 'instance' typeOf(new Error('teamocil')); // 'error'
// 'normal' JavaScript object typeOf({ a: 'b' }); // 'object' ```
typeOf @ember/utils
Parameter item
the item to check {String} the type
Modifiers
@public
type TypeName
type TypeName = | 'undefined' | 'null' | 'string' | 'number' | 'boolean' | 'function' | 'array' | 'regexp' | 'date' | 'filelist' | 'class' | 'instance' | 'error' | 'object';
namespace @ember/version
module '@ember/version' {}
variable VERSION
const VERSION: string;
namespace @glimmer/tracking
module '@glimmer/tracking' {}
variable cached
const cached: MethodDecorator;
Modifiers
@public
function tracked
tracked: { (propertyDesc: { value: any; initializer: () => any }): ExtendedMethodDecorator; (target: object, key: string): void; ( target: object, key: string, desc: PropertyDescriptor & { initializer?: any } ): PropertyDescriptor & { initializer?: any };};
Parameter dependencies
Optional dependents to be tracked.
Example 1
No dependencies
If you don't pass an argument to
@tracked
, only changes to that property will be tracked:```typescript import Component from '@glimmer/component'; import { tracked } from '@glimmer/tracking';
export default class MyComponent extends Component { remainingApples = 10 } ```
When something changes the component's
remainingApples
property, the rerender will be scheduled.Example 2
Dependents
In the case that you have a computed property that depends other properties, you want to track both so that when one of the dependents change, a rerender is scheduled.
In the following example we have two properties,
eatenApples
, andremainingApples
.```typescript import Component from '@glimmer/component'; import { tracked } from '@glimmer/tracking';
const totalApples = 100;
export default class MyComponent extends Component { eatenApples = 0
get remainingApples() { return totalApples - this.eatenApples; }
increment() { this.eatenApples = this.eatenApples + 1; } } ```
namespace @glimmer/tracking/primitives/cache
module '@glimmer/tracking/primitives/cache' {}
namespace ember
module 'ember' {}
namespace ember-template-compiler
module 'ember-template-compiler' {}
variable RESOLUTION_MODE_TRANSFORMS
const RESOLUTION_MODE_TRANSFORMS: readonly ((env: any) => ASTPlugin)[];
variable STRICT_MODE_TRANSFORMS
const STRICT_MODE_TRANSFORMS: readonly ((env: any) => ASTPlugin)[];
variable VERSION
const VERSION: string;
function compile
compile: ( templateString: string, options?: Partial<EmberPrecompileOptions>) => TemplateFactory;
Uses HTMLBars
compile
function to process a string into a compiled template. This is not present in production builds. compileParameter templateString
This is the string to be compiled by HTMLBars.
Parameter options
This is an options hash to augment the compiler options.
function compileOptions
compileOptions: ( _options?: Partial<EmberPrecompileOptions>) => EmberPrecompileOptions;
function precompile
precompile: ( templateString: string, options?: Partial<EmberPrecompileOptions>) => string;
Uses HTMLBars
compile
function to process a string into a compiled template string. The returned string must be passed throughEmber.HTMLBars.template
.This is not present in production builds.
precompile
Parameter templateString
This is the string to be compiled by HTMLBars.
interface EmberPrecompileOptions
interface EmberPrecompileOptions extends PrecompileOptions {}
property isProduction
isProduction?: boolean;
property lexicalScope
lexicalScope?: (name: string) => boolean;
property moduleName
moduleName?: string;
property plugins
plugins?: Plugins;
namespace ember-template-compiler/lib/-internal
module 'ember-template-compiler/lib/-internal' {}
variable INTERNAL_PLUGINS
const INTERNAL_PLUGINS: { readonly AssertAgainstAttrs: typeof AssertAgainstAttrs; readonly AssertAgainstNamedOutlets: typeof AssertAgainstNamedOutlets; readonly AssertInputHelperWithoutBlock: typeof AssertInputHelperWithoutBlock; readonly AssertReservedNamedArguments: typeof AssertReservedNamedArguments; readonly TransformActionSyntax: typeof TransformActionSyntax; readonly TransformEachInIntoEach: typeof TransformEachInIntoEach; readonly TransformEachTrackArray: typeof TransformEachTrackArray; readonly TransformInElement: typeof TransformInElement; readonly TransformQuotedBindingsIntoJustBindings: typeof TransformQuotedBindingsIntoJustBindings; readonly TransformResolutions: typeof TransformResolutions; readonly TransformWrapMountAndOutlet: typeof TransformWrapMountAndOutlet;};
namespace ember-template-compiler/lib/plugins
module 'ember-template-compiler/lib/plugins' {}
variable INTERNAL_PLUGINS
const INTERNAL_PLUGINS: { readonly AssertAgainstAttrs: typeof import('@ember/template-compiler/lib/plugins/assert-against-attrs').default; readonly AssertAgainstNamedOutlets: typeof import('@ember/template-compiler/lib/plugins/assert-against-named-outlets').default; readonly AssertInputHelperWithoutBlock: typeof import('@ember/template-compiler/lib/plugins/assert-input-helper-without-block').default; readonly AssertReservedNamedArguments: typeof import('@ember/template-compiler/lib/plugins/assert-reserved-named-arguments').default; readonly TransformActionSyntax: typeof import('@ember/template-compiler/lib/plugins/transform-action-syntax').default; readonly TransformEachInIntoEach: typeof import('@ember/template-compiler/lib/plugins/transform-each-in-into-each').default; readonly TransformEachTrackArray: typeof import('@ember/template-compiler/lib/plugins/transform-each-track-array').default; readonly TransformInElement: typeof import('@ember/template-compiler/lib/plugins/transform-in-element').default; readonly TransformQuotedBindingsIntoJustBindings: typeof import('@ember/template-compiler/lib/plugins/transform-quoted-bindings-into-just-bindings').default; readonly TransformResolutions: typeof import('@ember/template-compiler/lib/plugins/transform-resolutions').default; readonly TransformWrapMountAndOutlet: typeof import('@ember/template-compiler/lib/plugins/transform-wrap-mount-and-outlet').default;};
variable RESOLUTION_MODE_TRANSFORMS
const RESOLUTION_MODE_TRANSFORMS: readonly ((env: any) => ASTPlugin)[];
variable STRICT_MODE_KEYWORDS
const STRICT_MODE_KEYWORDS: readonly string[];
variable STRICT_MODE_TRANSFORMS
const STRICT_MODE_TRANSFORMS: readonly ((env: any) => ASTPlugin)[];
namespace ember-template-compiler/lib/plugins/assert-against-attrs
module 'ember-template-compiler/lib/plugins/assert-against-attrs' {}
variable _default
const _default: (env: any) => ASTPlugin;
namespace ember-template-compiler/lib/plugins/assert-against-named-outlets
module 'ember-template-compiler/lib/plugins/assert-against-named-outlets' {}
variable _default
const _default: (env: any) => ASTPlugin;
namespace ember-template-compiler/lib/plugins/assert-input-helper-without-block
module 'ember-template-compiler/lib/plugins/assert-input-helper-without-block' {}
variable _default
const _default: (env: any) => ASTPlugin;
namespace ember-template-compiler/lib/plugins/assert-reserved-named-arguments
module 'ember-template-compiler/lib/plugins/assert-reserved-named-arguments' {}
variable _default
const _default: (env: any) => ASTPlugin;
namespace ember-template-compiler/lib/plugins/transform-action-syntax
module 'ember-template-compiler/lib/plugins/transform-action-syntax' {}
variable _default
const _default: (env: any) => ASTPlugin;
namespace ember-template-compiler/lib/plugins/transform-each-in-into-each
module 'ember-template-compiler/lib/plugins/transform-each-in-into-each' {}
variable _default
const _default: (env: any) => ASTPlugin;
namespace ember-template-compiler/lib/plugins/transform-each-track-array
module 'ember-template-compiler/lib/plugins/transform-each-track-array' {}
variable _default
const _default: (env: any) => ASTPlugin;
namespace ember-template-compiler/lib/plugins/transform-in-element
module 'ember-template-compiler/lib/plugins/transform-in-element' {}
variable _default
const _default: (env: any) => ASTPlugin;
namespace ember-template-compiler/lib/plugins/transform-quoted-bindings-into-just-bindings
module 'ember-template-compiler/lib/plugins/transform-quoted-bindings-into-just-bindings' {}
variable _default
const _default: () => ASTPlugin;
namespace ember-template-compiler/lib/plugins/transform-resolutions
module 'ember-template-compiler/lib/plugins/transform-resolutions' {}
variable _default
const _default: (env: any) => ASTPlugin;
namespace ember-template-compiler/lib/plugins/transform-wrap-mount-and-outlet
module 'ember-template-compiler/lib/plugins/transform-wrap-mount-and-outlet' {}
variable _default
const _default: (env: any) => ASTPlugin;
namespace ember-template-compiler/lib/plugins/utils
module 'ember-template-compiler/lib/plugins/utils' {}
function inScope
inScope: (env: EmberASTPluginEnvironment, name: string) => boolean;
function isPath
isPath: (node: AST.Node) => node is AST.PathExpression;
function isStringLiteral
isStringLiteral: (node: AST.Expression) => node is AST.StringLiteral;
function trackLocals
trackLocals: (env: EmberASTPluginEnvironment) => { hasLocal: (key: string) => boolean; node: { enter(node: AST.Template | AST.Block | AST.ElementNode): void; exit(node: AST.Template | AST.Block | AST.ElementNode): void; }; visitor: { Template: { enter(node: AST.Template | AST.Block | AST.ElementNode): void; exit(node: AST.Template | AST.Block | AST.ElementNode): void; }; ElementNode: { enter(node: AST.Template | AST.Block | AST.ElementNode): void; exit(node: AST.Template | AST.Block | AST.ElementNode): void; }; Block: { enter(node: AST.Template | AST.Block | AST.ElementNode): void; exit(node: AST.Template | AST.Block | AST.ElementNode): void; }; };};
namespace ember-template-compiler/lib/public-api
module 'ember-template-compiler/lib/public-api' {}
variable RESOLUTION_MODE_TRANSFORMS
const RESOLUTION_MODE_TRANSFORMS: readonly ((env: any) => ASTPlugin)[];
variable STRICT_MODE_TRANSFORMS
const STRICT_MODE_TRANSFORMS: readonly ((env: any) => ASTPlugin)[];
variable VERSION
const VERSION: string;
function compile
compile: ( templateString: string, options?: Partial<EmberPrecompileOptions>) => TemplateFactory;
Uses HTMLBars
compile
function to process a string into a compiled template. This is not present in production builds. compileParameter templateString
This is the string to be compiled by HTMLBars.
Parameter options
This is an options hash to augment the compiler options.
function compileOptions
compileOptions: ( _options?: Partial<EmberPrecompileOptions>) => EmberPrecompileOptions;
function precompile
precompile: ( templateString: string, options?: Partial<EmberPrecompileOptions>) => string;
Uses HTMLBars
compile
function to process a string into a compiled template string. The returned string must be passed throughEmber.HTMLBars.template
.This is not present in production builds.
precompile
Parameter templateString
This is the string to be compiled by HTMLBars.
interface EmberPrecompileOptions
interface EmberPrecompileOptions extends PrecompileOptions {}
property isProduction
isProduction?: boolean;
property lexicalScope
lexicalScope?: (name: string) => boolean;
property moduleName
moduleName?: string;
property plugins
plugins?: Plugins;
namespace ember-template-compiler/lib/system/bootstrap
module 'ember-template-compiler/lib/system/bootstrap' {}
function bootstrap
bootstrap: ({ context, hasTemplate, setTemplate }: BootstrapOptions) => void;
Find templates stored in the head tag as script tags and make them available to
Ember.CoreView
in the globalEmber.TEMPLATES
object.Script tags with
text/x-handlebars
will be compiled with Ember's template compiler and are suitable for use as a view's template.bootstrap Ember.HTMLBars
Parameter ctx
interface BootstrapOptions
interface BootstrapOptions {}
property context
context?: Document | HTMLElement;
method hasTemplate
hasTemplate: (templateName: string) => boolean;
method setTemplate
setTemplate: (templateName: string, template: TemplateFactory) => void;
namespace ember-template-compiler/lib/system/calculate-location-display
module 'ember-template-compiler/lib/system/calculate-location-display' {}
function calculateLocationDisplay
calculateLocationDisplay: ( moduleName: string | undefined, loc?: AST.SourceLocation | undefined) => string;
namespace ember-template-compiler/lib/system/compile
module 'ember-template-compiler/lib/system/compile' {}
function compile
compile: ( templateString: string, options?: Partial<EmberPrecompileOptions>) => TemplateFactory;
Uses HTMLBars
compile
function to process a string into a compiled template. This is not present in production builds. compileParameter templateString
This is the string to be compiled by HTMLBars.
Parameter options
This is an options hash to augment the compiler options.
namespace ember-template-compiler/lib/system/compile-options
module 'ember-template-compiler/lib/system/compile-options' {}
function buildCompileOptions
buildCompileOptions: ( _options: EmberPrecompileOptions) => EmberPrecompileOptions;
function compileOptions
compileOptions: ( _options?: Partial<EmberPrecompileOptions>) => EmberPrecompileOptions;
function transformsFor
transformsFor: (options: EmberPrecompileOptions) => readonly PluginFunc[];
namespace ember-template-compiler/lib/system/dasherize-component-name
module 'ember-template-compiler/lib/system/dasherize-component-name' {}
variable _default
const _default: Cache<string, string>;
namespace ember-template-compiler/lib/system/initializer
module 'ember-template-compiler/lib/system/initializer' {}
namespace ember-template-compiler/lib/system/precompile
module 'ember-template-compiler/lib/system/precompile' {}
function precompile
precompile: ( templateString: string, options?: Partial<EmberPrecompileOptions>) => string;
Uses HTMLBars
compile
function to process a string into a compiled template string. The returned string must be passed throughEmber.HTMLBars.template
.This is not present in production builds.
precompile
Parameter templateString
This is the string to be compiled by HTMLBars.
namespace ember-template-compiler/lib/types
module 'ember-template-compiler/lib/types' {}
interface EmberPrecompileOptions
interface EmberPrecompileOptions extends PrecompileOptions {}
property isProduction
isProduction?: boolean;
property lexicalScope
lexicalScope?: (name: string) => boolean;
property moduleName
moduleName?: string;
property plugins
plugins?: Plugins;
interface PluginFunc
interface PluginFunc extends ASTPluginBuilder<EmberASTPluginEnvironment> {}
type Builders
type Builders = typeof builders;
type EmberASTPluginEnvironment
type EmberASTPluginEnvironment = ASTPluginEnvironment & EmberPrecompileOptions;
namespace ember-template-compiler/minimal
module 'ember-template-compiler/minimal' {}
function precompile
precompile: ( templateString: string, options?: Partial<EmberPrecompileOptions>) => string;
Uses HTMLBars
compile
function to process a string into a compiled template string. The returned string must be passed throughEmber.HTMLBars.template
.This is not present in production builds.
precompile
Parameter templateString
This is the string to be compiled by HTMLBars.
namespace ember-testing
module 'ember-testing' {}
variable Adapter
const Adapter: Readonly<typeof EmberObject> & (new (owner?: import('@ember/owner').default | undefined) => EmberObject) & { asyncStart(): void; asyncEnd(): void; exception(error: unknown): never; };
variable QUnitAdapter
const QUnitAdapter: Readonly< Readonly<typeof EmberObject> & (new ( owner?: import('@ember/owner').default | undefined ) => import('@ember/object').default) & { asyncStart(): void; asyncEnd(): void; exception(error: unknown): never; }> & (new ( owner?: import('@ember/owner').default | undefined ) => import('@ember/object').default) & { init(this: QUnitAdapter): void; asyncStart(this: QUnitAdapter): void; asyncEnd(this: QUnitAdapter): void; exception(error: unknown): void; };
variable Test
const Test: { _helpers: Record< string, { method: import('@ember/-internals/utility-types').AnyFn; meta: { wait: boolean }; } >; registerHelper: typeof registerHelper; registerAsyncHelper: typeof registerAsyncHelper; unregisterHelper: typeof unregisterHelper; onInjectHelpers: typeof onInjectHelpers; Promise: typeof TestPromise; promise: typeof promise; resolve: typeof resolve; registerWaiter: typeof registerWaiter; unregisterWaiter: typeof unregisterWaiter; checkWaiters: typeof checkWaiters;};
This is a container for an assortment of testing related functionality:
Choose your default test adapter (for your framework of choice). Register/Unregister additional test helpers. Setup callbacks to be fired when the test helpers are injected into your application.
Test Ember
Modifiers
@public
function setupForTesting
setupForTesting: () => void;
Sets Ember up for testing. This is useful to perform basic setup steps in order to unit test.
Use
App.setupForTesting
to perform integration tests (full application testing).setupForTesting Ember 1.5.0
interface Adapter
interface Adapter extends EmberObject {}
The primary purpose of this class is to create hooks that can be implemented by an adapter for various test frameworks.
TestAdapter
Modifiers
@public
method asyncEnd
asyncEnd: () => void;
method asyncStart
asyncStart: () => void;
method exception
exception: (error: unknown) => never;
interface QUnitAdapter
interface QUnitAdapter extends Adapter {}
This class implements the methods defined by TestAdapter for the QUnit testing framework.
QUnitAdapter Ember.Test TestAdapter
Modifiers
@public
property doneCallbacks
doneCallbacks: Array<Function>;
namespace ember-testing/lib/adapters/adapter
module 'ember-testing/lib/adapters/adapter' {}
variable Adapter
const Adapter: Readonly<typeof EmberObject> & (new (owner?: import('@ember/owner').default | undefined) => EmberObject) & { asyncStart(): void; asyncEnd(): void; exception(error: unknown): never; };
interface Adapter
interface Adapter extends EmberObject {}
The primary purpose of this class is to create hooks that can be implemented by an adapter for various test frameworks.
TestAdapter
Modifiers
@public
method asyncEnd
asyncEnd: () => void;
method asyncStart
asyncStart: () => void;
method exception
exception: (error: unknown) => never;
namespace ember-testing/lib/adapters/qunit
module 'ember-testing/lib/adapters/qunit' {}
variable QUnitAdapter
const QUnitAdapter: Readonly< Readonly<typeof EmberObject> & (new ( owner?: import('@ember/owner').default | undefined ) => import('@ember/object').default) & { asyncStart(): void; asyncEnd(): void; exception(error: unknown): never; }> & (new ( owner?: import('@ember/owner').default | undefined ) => import('@ember/object').default) & { init(this: QUnitAdapter): void; asyncStart(this: QUnitAdapter): void; asyncEnd(this: QUnitAdapter): void; exception(error: unknown): void; };
interface QUnitAdapter
interface QUnitAdapter extends Adapter {}
This class implements the methods defined by TestAdapter for the QUnit testing framework.
QUnitAdapter Ember.Test TestAdapter
Modifiers
@public
property doneCallbacks
doneCallbacks: Array<Function>;
namespace ember-testing/lib/ext/application
module 'ember-testing/lib/ext/application' {}
interface TestableApp
interface TestableApp extends Application {}
property helperContainer
helperContainer: object | null;
property originalMethods
originalMethods: Record<string, (...args: unknown[]) => unknown>;
property testHelpers
testHelpers: Record<string, (...args: unknown[]) => unknown>;
property testing
testing?: boolean;
method injectTestHelpers
injectTestHelpers: (helperContainer: unknown) => void;
method removeTestHelpers
removeTestHelpers: () => void;
method setupForTesting
setupForTesting: () => void;
namespace ember-testing/lib/ext/rsvp
module 'ember-testing/lib/ext/rsvp' {}
namespace ember-testing/lib/helpers
module 'ember-testing/lib/helpers' {}
namespace ember-testing/lib/helpers/and_then
module 'ember-testing/lib/helpers/and_then' {}
function andThen
andThen: (app: TestableApp, callback: (app: TestableApp) => unknown) => unknown;
namespace ember-testing/lib/helpers/current_path
module 'ember-testing/lib/helpers/current_path' {}
function currentPath
currentPath: (app: Application) => string | null;
Returns the current path.
Example:
```javascript function validateURL() { equal(currentPath(), 'some.path.index', "correct path was transitioned into."); }
click('#some-link-id').then(validateURL); ```
currentPath {Object} The currently active path. 1.5.0
Modifiers
@public
namespace ember-testing/lib/helpers/current_route_name
module 'ember-testing/lib/helpers/current_route_name' {}
function currentRouteName
currentRouteName: (app: Application) => string | null;
Returns the currently active route name.
Example:
```javascript function validateRouteName() { equal(currentRouteName(), 'some.path', "correct route was transitioned into."); } visit('/some/path').then(validateRouteName) ```
currentRouteName {Object} The name of the currently active route. 1.5.0
Modifiers
@public
namespace ember-testing/lib/helpers/current_url
module 'ember-testing/lib/helpers/current_url' {}
function currentURL
currentURL: (app: Application) => string;
Returns the current URL.
Example:
```javascript function validateURL() { equal(currentURL(), '/some/path', "correct URL was transitioned into."); }
click('#some-link-id').then(validateURL); ```
currentURL {Object} The currently active URL. 1.5.0
Modifiers
@public
namespace ember-testing/lib/helpers/pause_test
module 'ember-testing/lib/helpers/pause_test' {}
function pauseTest
pauseTest: () => RSVP.default.Promise<unknown>;
Pauses the current test - this is useful for debugging while testing or for test-driving. It allows you to inspect the state of your application at any point. Example (The test will pause before clicking the button):
```javascript visit('/') return pauseTest(); click('.btn'); ```
You may want to turn off the timeout before pausing.
qunit (timeout available to use as of 2.4.0):
``` visit('/'); assert.timeout(0); return pauseTest(); click('.btn'); ```
mocha (timeout happens automatically as of ember-mocha v0.14.0):
``` visit('/'); this.timeout(0); return pauseTest(); click('.btn'); ```
1.9.0 pauseTest {Object} A promise that will never resolve
Modifiers
@public
function resumeTest
resumeTest: () => void;
Resumes a test paused by
pauseTest
.resumeTest {void}
Modifiers
@public
namespace ember-testing/lib/helpers/visit
module 'ember-testing/lib/helpers/visit' {}
function visit
visit: (app: TestableApp, url: string) => unknown;
Loads a route, sets up any controllers, and renders any templates associated with the route as though a real user had triggered the route change while using your app.
Example:
```javascript visit('posts/index').then(function() { // assert something }); ```
visit
Parameter url
the name of the route {RSVP.Promise}
Modifiers
@public
namespace ember-testing/lib/helpers/wait
module 'ember-testing/lib/helpers/wait' {}
function wait
wait: <T>(app: Application, value: T) => Promise<T>;
Causes the run loop to process any pending events. This is used to ensure that any async operations from other helpers (or your assertions) have been processed.
This is most often used as the return value for the helper functions (see 'click', 'fillIn','visit',etc). However, there is a method to register a test helper which utilizes this method without the need to actually call
wait()
in your helpers.The
wait
helper is built intoregisterAsyncHelper
by default. You will not need toreturn app.testHelpers.wait();
- the wait behavior is provided for you.Example:
```javascript import { registerAsyncHelper } from '@ember/test';
registerAsyncHelper('loginUser', function(app, username, password) { visit('secured/path/here') .fillIn('#username', username) .fillIn('#password', password) .click('.submit'); }); ```
wait
Parameter value
The value to be returned. {RSVP.Promise} Promise that resolves to the passed value.
1.0.0
Modifiers
@public
namespace ember-testing/lib/initializers
module 'ember-testing/lib/initializers' {}
namespace ember-testing/lib/public-api
module 'ember-testing/lib/public-api' {}
variable Adapter
const Adapter: Readonly<typeof EmberObject> & (new (owner?: import('@ember/owner').default | undefined) => EmberObject) & { asyncStart(): void; asyncEnd(): void; exception(error: unknown): never; };
variable QUnitAdapter
const QUnitAdapter: Readonly< Readonly<typeof EmberObject> & (new ( owner?: import('@ember/owner').default | undefined ) => import('@ember/object').default) & { asyncStart(): void; asyncEnd(): void; exception(error: unknown): never; }> & (new ( owner?: import('@ember/owner').default | undefined ) => import('@ember/object').default) & { init(this: QUnitAdapter): void; asyncStart(this: QUnitAdapter): void; asyncEnd(this: QUnitAdapter): void; exception(error: unknown): void; };
variable Test
const Test: { _helpers: Record< string, { method: import('@ember/-internals/utility-types').AnyFn; meta: { wait: boolean }; } >; registerHelper: typeof registerHelper; registerAsyncHelper: typeof registerAsyncHelper; unregisterHelper: typeof unregisterHelper; onInjectHelpers: typeof onInjectHelpers; Promise: typeof TestPromise; promise: typeof promise; resolve: typeof resolve; registerWaiter: typeof registerWaiter; unregisterWaiter: typeof unregisterWaiter; checkWaiters: typeof checkWaiters;};
This is a container for an assortment of testing related functionality:
Choose your default test adapter (for your framework of choice). Register/Unregister additional test helpers. Setup callbacks to be fired when the test helpers are injected into your application.
Test Ember
Modifiers
@public
function setupForTesting
setupForTesting: () => void;
Sets Ember up for testing. This is useful to perform basic setup steps in order to unit test.
Use
App.setupForTesting
to perform integration tests (full application testing).setupForTesting Ember 1.5.0
interface Adapter
interface Adapter extends EmberObject {}
The primary purpose of this class is to create hooks that can be implemented by an adapter for various test frameworks.
TestAdapter
Modifiers
@public
method asyncEnd
asyncEnd: () => void;
method asyncStart
asyncStart: () => void;
method exception
exception: (error: unknown) => never;
interface QUnitAdapter
interface QUnitAdapter extends Adapter {}
This class implements the methods defined by TestAdapter for the QUnit testing framework.
QUnitAdapter Ember.Test TestAdapter
Modifiers
@public
property doneCallbacks
doneCallbacks: Array<Function>;
namespace ember-testing/lib/setup_for_testing
module 'ember-testing/lib/setup_for_testing' {}
function setupForTesting
setupForTesting: () => void;
Sets Ember up for testing. This is useful to perform basic setup steps in order to unit test.
Use
App.setupForTesting
to perform integration tests (full application testing).setupForTesting Ember 1.5.0
namespace ember-testing/lib/test
module 'ember-testing/lib/test' {}
variable Test
const Test: { _helpers: Record< string, { method: import('@ember/-internals/utility-types').AnyFn; meta: { wait: boolean }; } >; registerHelper: typeof registerHelper; registerAsyncHelper: typeof registerAsyncHelper; unregisterHelper: typeof unregisterHelper; onInjectHelpers: typeof onInjectHelpers; Promise: typeof TestPromise; promise: typeof promise; resolve: typeof resolve; registerWaiter: typeof registerWaiter; unregisterWaiter: typeof unregisterWaiter; checkWaiters: typeof checkWaiters;};
This is a container for an assortment of testing related functionality:
Choose your default test adapter (for your framework of choice). Register/Unregister additional test helpers. Setup callbacks to be fired when the test helpers are injected into your application.
Test Ember
Modifiers
@public
namespace ember-testing/lib/test/adapter
module 'ember-testing/lib/test/adapter' {}
function asyncEnd
asyncEnd: () => void;
function asyncStart
asyncStart: () => void;
function getAdapter
getAdapter: () => Adapter;
function setAdapter
setAdapter: (value: Adapter) => void;
namespace ember-testing/lib/test/helpers
module 'ember-testing/lib/test/helpers' {}
variable helpers
const helpers: Record<string, { method: AnyFn; meta: { wait: boolean } }>;
function registerAsyncHelper
registerAsyncHelper: (name: string, helperMethod: AnyFn) => void;
registerAsyncHelper
is used to register an async test helper that will be injected whenApp.injectTestHelpers
is called.The helper method will always be called with the current Application as the first parameter.
For example:
```javascript import { registerAsyncHelper } from '@ember/test'; import { run } from '@ember/runloop';
registerAsyncHelper('boot', function(app) { run(app, app.advanceReadiness); }); ```
The advantage of an async helper is that it will not run until the last async helper has completed. All async helpers after it will wait for it complete before running.
For example:
```javascript import { registerAsyncHelper } from '@ember/test';
registerAsyncHelper('deletePost', function(app, postId) { click('.delete-' + postId); });
// ... in your test visit('/post/2'); deletePost(2); visit('/post/3'); deletePost(3); ```
@ember/test registerAsyncHelper
Parameter name
The name of the helper method to add.
Parameter helperMethod
1.2.0
Modifiers
@public
function registerHelper
registerHelper: ( name: string, helperMethod: (app: Application, ...args: any[]) => unknown) => void;
registerHelper
is used to register a test helper that will be injected whenApp.injectTestHelpers
is called.The helper method will always be called with the current Application as the first parameter.
For example:
```javascript import { registerHelper } from '@ember/test'; import { run } from '@ember/runloop';
registerHelper('boot', function(app) { run(app, app.advanceReadiness); }); ```
This helper can later be called without arguments because it will be called with
app
as the first parameter.```javascript import Application from '@ember/application';
App = Application.create(); App.injectTestHelpers(); boot(); ```
@ember/test registerHelper
Parameter name
The name of the helper method to add.
Parameter helperMethod
Parameter options
Modifiers
@public
function unregisterHelper
unregisterHelper: (name: string) => void;
Remove a previously added helper method.
Example:
```javascript import { unregisterHelper } from '@ember/test';
unregisterHelper('wait'); ```
unregisterHelper @ember/test
Parameter name
The helper to remove.
Modifiers
@public
namespace ember-testing/lib/test/on_inject_helpers
module 'ember-testing/lib/test/on_inject_helpers' {}
variable callbacks
const callbacks: ((app: Application) => void)[];
function invokeInjectHelpersCallbacks
invokeInjectHelpersCallbacks: (app: Application) => void;
function onInjectHelpers
onInjectHelpers: (callback: (app: Application) => void) => void;
Used to register callbacks to be fired whenever
App.injectTestHelpers
is called.The callback will receive the current application as an argument.
Example:
```javascript import $ from 'jquery';
Ember.Test.onInjectHelpers(function() { $(document).ajaxSend(function() { Test.pendingRequests++; });
$(document).ajaxComplete(function() { Test.pendingRequests--; }); }); ```
Ember.Test onInjectHelpers
Parameter callback
The function to be called.
Modifiers
@public
namespace ember-testing/lib/test/pending_requests
module 'ember-testing/lib/test/pending_requests' {}
function clearPendingRequests
clearPendingRequests: () => void;
function decrementPendingRequests
decrementPendingRequests: (_: unknown, xhr: unknown) => void;
function incrementPendingRequests
incrementPendingRequests: (_: unknown, xhr: unknown) => void;
function pendingRequests
pendingRequests: () => number;
namespace ember-testing/lib/test/promise
module 'ember-testing/lib/test/promise' {}
function getLastPromise
getLastPromise: () => TestPromise<unknown> | null;
function promise
promise: <T>(resolver: Executor<T>, label?: string) => TestPromise<T>;
This returns a thenable tailored for testing. It catches failed
onSuccess
callbacks and invokes theEmber.Test.adapter.exception
callback in the last chained then.This method should be returned by async helpers such as
wait
.Ember.Test promise
Parameter resolver
The function used to resolve the promise.
Parameter label
An optional string for identifying the promise.
Modifiers
@public
function resolve
resolve: (result: unknown, label?: string) => RSVP.default.Promise<unknown>;
Replacement for
Ember.RSVP.resolve
The only difference is this uses an instance ofEmber.Test.Promise
Ember.Test resolve
Parameter The
value to resolve 1.2.0
Modifiers
@public
class TestPromise
class TestPromise<T> extends RSVP.Promise<T> {}
constructor
constructor(executor: Executor<T>, label?: string);
method then
then: <TResult1 = T, TResult2 = never>( onFulfilled?: OnFulfilled<T, TResult1> | null, onRejected?: (reason: any) => TResult2 | PromiseLike<TResult2>, label?: string) => RSVP.Promise<TResult1 | TResult2>;
namespace ember-testing/lib/test/run
module 'ember-testing/lib/test/run' {}
function run
run: <T>(fn: () => T) => T;
namespace ember-testing/lib/test/waiters
module 'ember-testing/lib/test/waiters' {}
function checkWaiters
checkWaiters: () => boolean;
Iterates through each registered test waiter, and invokes its callback. If any waiter returns false, this method will return true indicating that the waiters have not settled yet.
This is generally used internally from the acceptance/integration test infrastructure.
@ember/test checkWaiters
Modifiers
@public
function registerWaiter
registerWaiter: { <T>(context: T, callback: (this: T) => unknown): void; (callback: (this: null) => unknown): void;};
This allows ember-testing to play nicely with other asynchronous events, such as an application that is waiting for a CSS3 transition or an IndexDB transaction. The waiter runs periodically after each async helper (i.e.
click
,andThen
,visit
, etc) has executed, until the returning result is truthy. After the waiters finish, the next async helper is executed and the process repeats.For example:
```javascript import { registerWaiter } from '@ember/test';
registerWaiter(function() { return myPendingTransactions() === 0; }); ``` The
context
argument allows you to optionally specify thethis
with which your callback will be invoked.For example:
```javascript import { registerWaiter } from '@ember/test';
registerWaiter(MyDB, MyDB.hasPendingTransactions); ```
@ember/test registerWaiter
Parameter context
(optional)
Parameter callback
1.2.0
Modifiers
@public
function unregisterWaiter
unregisterWaiter: (context: unknown, callback: unknown) => void;
unregisterWaiter
is used to unregister a callback that was registered withregisterWaiter
.@ember/test unregisterWaiter
Parameter context
(optional)
Parameter callback
1.2.0
Modifiers
@public
namespace ember.Ember
namespace ember.Ember {}
variable ActionHandler
const ActionHandler: EmberMixin;
variable addListener
const addListener: ( obj: object, eventName: string, target: object | Function, method?: Function | PropertyKey, once?: boolean, sync?: boolean) => void;
variable addObserver
const addObserver: ( obj: any, path: string, target: object | Function, method?: string | Function, sync?: boolean) => void;
variable Application
const Application: typeof EmberApplication;
variable ApplicationInstance
const ApplicationInstance: typeof EmberApplicationInstance;
variable Array
const Array: EmberMixin;
variable ArrayProxy
const ArrayProxy: typeof EmberArrayProxy;
variable assert
const assert: AssertFunc;
variable beginPropertyChanges
const beginPropertyChanges: () => void;
variable BOOTED
let BOOTED: boolean;
Whether searching on the global for new Namespace instances is enabled.
This is only exported here as to not break any addons. Given the new visit API, you will have issues if you treat this as a indicator of booted.
Internally this is only exposing a flag in Namespace.
BOOTED Ember Boolean
variable cacheFor
const cacheFor: { <T, K extends keyof T>(obj: T, key: K): T[K]; (obj: object, key: string): unknown;};
variable canInvoke
const canInvoke: (obj: unknown, methodName: string) => boolean;
variable changeProperties
const changeProperties: (callback: () => void) => void;
variable Comparable
const Comparable: EmberMixin;
variable compare
const compare: <T>(v: T, w: T) => Compare;
variable Component
const Component: typeof EmberComponent;
variable ComponentLookup
const ComponentLookup: Readonly<typeof EmberObject> & (new (owner?: import('@ember/owner').default | undefined) => EmberObject) & { componentFor( name: string, owner: import('@ember/-internals/owner').InternalOwner ): import('@ember/owner').FactoryManager<object> | undefined; layoutFor( name: string, owner: import('@ember/-internals/owner').InternalOwner, options: import('@ember/owner').RegisterOptions ): unknown; };
variable computed
const computed: { ( target: object, propertyName: string, descriptor: PropertyDescriptor & { initializer?: any } ): void | (PropertyDescriptor & { initializer?: any }); (...dependentKeys: string[]): metal.ComputedDecorator; (...args: ComputedDecoratorKeysAndConfig): metal.ComputedDecorator; (callback: metal.ComputedPropertyCallback): metal.ComputedDecorator;};
variable ComputedProperty
const ComputedProperty: typeof metal.ComputedProperty;
variable Container
const Container: typeof InternalContainer;
variable ContainerDebugAdapter
const ContainerDebugAdapter: typeof EmberContainerDebugAdapter;
variable Controller
const Controller: typeof EmberController;
variable controllerFor
const controllerFor: ( container: InternalContainer, controllerName: string, lookupOptions: RegisterOptions) => object | InternalFactory<object, FactoryClass>;
variable ControllerMixin
const ControllerMixin: EmberMixin;
variable CoreObject
const CoreObject: typeof EmberCoreObject;
variable DataAdapter
const DataAdapter: typeof EmberDataAdapter;
variable debug
const debug: EmberDebug.DebugFunc;
variable Debug
const Debug: { registerDeprecationHandler: ( handler: import('@ember/debug/lib/handlers').HandlerCallback<EmberDebug.DeprecationOptions> ) => void; registerWarnHandler: import('@ember/debug/lib/warn').RegisterHandlerFunc; isComputed: typeof metal.isComputed;};
variable defineProperty
const defineProperty: ( obj: object, keyName: string, desc?: PropertyDescriptor | metal.ExtendedMethodDecorator, data?: any, _meta?: Meta) => void;
variable deprecate
const deprecate: ( message: string, test?: boolean, options?: EmberDebug.DeprecationOptions) => void;
variable deprecateFunc
const deprecateFunc: EmberDebug.DeprecateFuncFunc;
variable destroy
const destroy: any;
variable endPropertyChanges
const endPropertyChanges: () => void;
variable Engine
const Engine: typeof EmberEngine;
variable EngineInstance
const EngineInstance: typeof EmberEngineInstance;
variable Enumerable
const Enumerable: EmberMixin;
variable ENV
const ENV: {};
variable EventDispatcher
const EventDispatcher: typeof views.EventDispatcher;
variable Evented
const Evented: EmberMixin;
variable expandProperties
const expandProperties: ( pattern: string, callback: (expansion: string) => void) => void;
variable FEATURES
const FEATURES: { isEnabled: typeof isEnabled };
variable generateController
const generateController: ( owner: Owner, controllerName: string) => EmberController<unknown>;
variable generateControllerFactory
const generateControllerFactory: ( owner: Owner, controllerName: string) => InternalFactory<{}, FactoryClass>;
variable generateGuid
const generateGuid: (obj: object, prefix?: string) => String;
variable get
const get: { <T extends object, K extends keyof T>(obj: T, keyName: K): T[K]; (obj: unknown, keyName: string): unknown;};
variable getProperties
const getProperties: { <T, K extends keyof T>(obj: T, list: K[]): Pick<T, K>; <T, K extends keyof T>(obj: T, ...list: K[]): Pick<T, K>; <K extends string>(obj: unknown, list: K[]): Record<K, unknown>; <K extends string>(obj: unknown, ...list: K[]): Record<K, unknown>;};
variable GUID_KEY
const GUID_KEY: string;
variable guidFor
const guidFor: (value: any) => string;
variable Handlebars
let Handlebars: EmberHandlebars;
variable HashLocation
const HashLocation: typeof EmberHashLocation;
variable hasListeners
const hasListeners: (obj: object, eventName: string) => boolean;
variable Helper
const Helper: typeof EmberHelper;
variable HistoryLocation
const HistoryLocation: typeof EmberHistoryLocation;
variable HTMLBars
let HTMLBars: EmberHTMLBars;
variable inspect
const inspect: (this: any, obj: any) => string;
variable instrument
const instrument: { <Result>(name: string, callback: InstrumentCallback<undefined, Result>): Result; <Binding, Result>( name: string, callback: InstrumentCallback<Binding, Result>, binding: Binding ): Result; <Result>( name: string, payload: object, callback: InstrumentCallback<undefined, Result> ): Result; <Binding, Result>( name: string, payload: object, callback: InstrumentCallback<Binding, Result>, binding: Binding ): Result;};
variable Instrumentation
const Instrumentation: { instrument: typeof instrumentation.instrument; subscribe: typeof instrumentation.subscribe; unsubscribe: typeof instrumentation.unsubscribe; reset: typeof instrumentation.reset;};
variable isArray
const isArray: (obj: unknown) => obj is EmberArray<unknown> | ArrayLike<unknown>;
variable isBlank
const isBlank: (obj: unknown) => boolean;
variable isEmpty
const isEmpty: (obj: unknown) => boolean;
variable isEqual
const isEqual: (a: unknown, b: unknown) => boolean;
variable isNamespace
const isNamespace: boolean;
variable isNone
const isNone: (obj: any) => obj is null;
variable isPresent
const isPresent: <T>(obj: T) => obj is T;
variable libraries
const libraries: metal.Libraries;
variable lookup
let lookup: Record<string, unknown>;
variable makeArray
const makeArray: <T, TT>(obj: T) => T extends TT[] ? T : T extends null ? [] : [T];
variable meta
const meta: { (obj: object): import('@ember/-internals/meta').Meta; _counters?: import('@ember/-internals/meta').MetaCounters | undefined;};
variable mixin
const mixin: (obj: object, ...args: any[]) => object;
variable Mixin
const Mixin: typeof EmberMixin;
variable MutableArray
const MutableArray: EmberMixin;
variable MutableEnumerable
const MutableEnumerable: EmberMixin;
variable Namespace
const Namespace: typeof EmberNamespace;
variable NativeArray
const NativeArray: EmberMixin;
variable NoneLocation
const NoneLocation: typeof EmberNoneLocation;
variable notifyPropertyChange
const notifyPropertyChange: ( obj: object, keyName: string, _meta?: Meta, value?: unknown) => void;
variable Object
const Object: typeof EmberObject;
variable ObjectProxy
const ObjectProxy: typeof EmberObjectProxy;
variable Observable
const Observable: EmberMixin;
variable observer
const observer: <T extends AnyFn>( ...args: | [propertyName: string, ...additionalPropertyNames: string[], func: T] | [ObserverDefinition<T>]) => T;
variable on
const on: <T extends AnyFn>(...args: [...eventNames: string[], func: T]) => T;
variable onerror
let onerror: (error: Error) => unknown;
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) { const payload = { stack: error.stack, otherInformation: 'whatever app state you want to provide' };
fetch('/report-error', { method: 'POST', body: JSON.stringify(payload) }); }; ```
Internally,
Ember.onerror
is used as Backburner's error handler.onerror Ember
Parameter error
the error object
Modifiers
@public
variable onLoad
const onLoad: (name: string, callback: (obj: any) => void) => void;
variable PromiseProxyMixin
const PromiseProxyMixin: EmberMixin;
variable Registry
const Registry: typeof InternalRegistry;
variable removeListener
const removeListener: ( obj: object, eventName: string, targetOrFunction: object | Function, functionOrName?: string | Function) => void;
variable removeObserver
const removeObserver: ( obj: any, path: string, target: object | Function, method?: string | Function, sync?: boolean) => void;
variable Route
const Route: typeof EmberRoute;
variable Router
const Router: typeof EmberRouter;
variable RouterDSL
const RouterDSL: typeof EmberRouterDSL;
variable run
const run: { <F extends () => any>(method: F): ReturnType<F>; <F extends AnyFn>(method: F, ...args: Parameters<F>): ReturnType<F>; <T, F extends (this: T, ...args: any[]) => any>( target: T, method: F, ...args: Parameters<F> ): ReturnType<F>; <T, U extends keyof T>( target: T, method: U, ...args: T[U] extends AnyFn ? Parameters<T[U]> : [] ): T[U] extends AnyFn ? ReturnType<T[U]> : unknown;};
variable runInDebug
const runInDebug: EmberDebug.RunInDebugFunc;
variable runLoadHooks
const runLoadHooks: (name: string, object: unknown) => void;
variable sendEvent
const sendEvent: ( obj: object, eventName: string, params?: any[], actions?: any[], _meta?: Meta) => boolean;
variable Service
const Service: typeof EmberService;
variable set
const set: <T>(obj: object, keyName: string, value: T, tolerant?: boolean) => T;
variable setOwner
const setOwner: (object: object, owner: Owner) => void;
variable setProperties
const setProperties: { <T, K extends keyof T>(obj: T, properties: Pick<T, K>): Pick<T, K>; <T extends Record<string, unknown>>(obj: object, properties: T): T;};
variable setupForTesting
let setupForTesting: () => void;
variable subscribe
const subscribe: <T>( pattern: string, object: instrumentation.Listener<T>) => instrumentation.Subscriber<T>;
variable TEMPLATES
let TEMPLATES: TemplatesRegistry;
Global hash of shared templates. This will automatically be populated by the build tools so that you can store your Handlebars templates in separate files that get loaded into JavaScript at buildtime.
TEMPLATES Ember Object
variable Test
let Test: { _helpers: Record<string, { method: AnyFn; meta: { wait: boolean } }>; registerHelper: ( name: string, helperMethod: (app: EmberApplication, ...args: any[]) => unknown ) => void; registerAsyncHelper: (name: string, helperMethod: AnyFn) => void; unregisterHelper: (name: string) => void; onInjectHelpers: (callback: (app: EmberApplication) => void) => void; Promise: typeof TestPromise; promise: <T>(resolver: Executor<T>, label?: string) => TestPromise<T>; resolve: (result: unknown, label?: string) => RSVP.default.Promise<unknown>; registerWaiter: { <T>(context: T, callback: (this: T) => unknown): void; (callback: (this: null) => unknown): void; }; unregisterWaiter: (context: unknown, callback: unknown) => void; checkWaiters: () => boolean;} & { Adapter: NonNullable<typeof EmberTestingImpl>['Adapter']; QUnitAdapter: NonNullable<typeof EmberTestingImpl>['QUnitAdapter'];};
variable testing
let testing: boolean;
variable trySet
const trySet: <T>(root: object, path: string, value: T) => T;
variable typeOf
const typeOf: (item: unknown) => TypeName;
variable uuid
const uuid: () => number;
variable VERSION
const VERSION: string;
The semantic version
VERSION String
Modifiers
@public
variable ViewUtils
const ViewUtils: { getChildViews: typeof views.getChildViews; getElementView: typeof views.getElementView; getRootViews: typeof views.getRootViews; getViewBounds: typeof views.getViewBounds; getViewBoundingClientRect: typeof views.getViewBoundingClientRect; getViewClientRects: typeof views.getViewClientRects; getViewElement: typeof views.getViewElement; isSimpleClick: typeof views.isSimpleClick; isSerializationFirstNode: any;};
variable warn
const warn: WarnFunc;
variable wrap
const wrap: (func: Function, superFunc: Function) => Function;
function A
A: <T>(arr?: T[]) => EmberNativeArray<T>;
function getOwner
getOwner: (object: object) => import('@ember/owner').default | undefined;
function inject
inject: typeof inject;
Namespace for injection helper methods.
inject Ember
Modifiers
@public
function toString
toString: () => string;
type ActionHandler
type ActionHandler = InternalActionHandler;
type Application
type Application = EmberApplication;
type ApplicationInstance
type ApplicationInstance = EmberApplicationInstance;
type Array
type Array<T> = EmberArray<T>;
type ArrayProxy
type ArrayProxy<T> = EmberArrayProxy<T>;
type Comparable
type Comparable = InternalComparable;
type Component
type Component<S = unknown> = EmberComponent<S>;
type ComputedProperty
type ComputedProperty = EmberComputedProperty;
type Container
type Container = InternalContainer;
type ContainerDebugAdapter
type ContainerDebugAdapter = EmberContainerDebugAdapter;
type Controller
type Controller<T = unknown> = EmberController<T>;
type ControllerMixin
type ControllerMixin<T> = EmberControllerMixin<T>;
type CoreObject
type CoreObject = EmberCoreObject;
type DataAdapter
type DataAdapter<T> = EmberDataAdapter<T>;
type Engine
type Engine = EmberEngine;
type EngineInstance
type EngineInstance = EmberEngineInstance;
type Enumerable
type Enumerable = EmberEnumerable;
type Evented
type Evented = EmberEvented;
type HashLocation
type HashLocation = EmberHashLocation;
type Helper
type Helper<S = unknown> = EmberHelper<S>;
type HistoryLocation
type HistoryLocation = EmberHistoryLocation;
type Mixin
type Mixin = EmberMixin;
type MutableArray
type MutableArray<T> = EmberMutableArray<T>;
type MutableEnumerable
type MutableEnumerable = EmberMutableEnumerable;
type Namespace
type Namespace = EmberNamespace;
type NativeArray
type NativeArray<T> = EmberNativeArray<T>;
type NoneLocation
type NoneLocation = EmberNoneLocation;
type Object
type Object = EmberObject;
type ObjectProxy
type ObjectProxy = EmberObjectProxy;
type Observable
type Observable = EmberObservable;
type PromiseProxyMixin
type PromiseProxyMixin<T> = EmberPromiseProxyMixin<T>;
type Registry
type Registry = InternalRegistry;
type Route
type Route = EmberRoute;
type Router
type Router = EmberRouter;
type RouterDSL
type RouterDSL = EmberRouterDSL;
type Service
type Service = EmberService;
namespace ember.Ember.inject
namespace ember.Ember.inject {}
variable controller
var controller: { (name: string): PropertyDecorator; (args_0: object, args_1: string): void; ( target: object, propertyName: string, descriptor?: PropertyDescriptor & { initializer?: any } ): PropertyDescriptor & { initializer?: any }; (): PropertyDecorator;};
variable service
var service: { (name: string): PropertyDecorator; (args_0: object, args_1: string): void; ( target: object, propertyName: string, descriptor?: PropertyDescriptor & { initializer?: any } ): PropertyDescriptor & { initializer?: any }; (): PropertyDecorator;};
namespace ember/barrel
module 'ember/barrel' {}
namespace ember/barrel.Ember
namespace ember/barrel.Ember {}
variable ActionHandler
const ActionHandler: EmberMixin;
variable addListener
const addListener: ( obj: object, eventName: string, target: object | Function, method?: Function | PropertyKey, once?: boolean, sync?: boolean) => void;
variable addObserver
const addObserver: ( obj: any, path: string, target: object | Function, method?: string | Function, sync?: boolean) => void;
variable Application
const Application: typeof EmberApplication;
variable ApplicationInstance
const ApplicationInstance: typeof EmberApplicationInstance;
variable Array
const Array: EmberMixin;
variable ArrayProxy
const ArrayProxy: typeof EmberArrayProxy;
variable assert
const assert: AssertFunc;
variable beginPropertyChanges
const beginPropertyChanges: () => void;
variable BOOTED
let BOOTED: boolean;
Whether searching on the global for new Namespace instances is enabled.
This is only exported here as to not break any addons. Given the new visit API, you will have issues if you treat this as a indicator of booted.
Internally this is only exposing a flag in Namespace.
BOOTED Ember Boolean
variable cacheFor
const cacheFor: { <T, K extends keyof T>(obj: T, key: K): T[K]; (obj: object, key: string): unknown;};
variable canInvoke
const canInvoke: (obj: unknown, methodName: string) => boolean;
variable changeProperties
const changeProperties: (callback: () => void) => void;
variable Comparable
const Comparable: EmberMixin;
variable compare
const compare: <T>(v: T, w: T) => Compare;
variable Component
const Component: typeof EmberComponent;
variable ComponentLookup
const ComponentLookup: Readonly<typeof EmberObject> & (new (owner?: import('@ember/owner').default | undefined) => EmberObject) & { componentFor( name: string, owner: import('@ember/-internals/owner').InternalOwner ): import('@ember/owner').FactoryManager<object> | undefined; layoutFor( name: string, owner: import('@ember/-internals/owner').InternalOwner, options: import('@ember/owner').RegisterOptions ): unknown; };
variable computed
const computed: { ( target: object, propertyName: string, descriptor: PropertyDescriptor & { initializer?: any } ): void | (PropertyDescriptor & { initializer?: any }); (...dependentKeys: string[]): metal.ComputedDecorator; (...args: ComputedDecoratorKeysAndConfig): metal.ComputedDecorator; (callback: metal.ComputedPropertyCallback): metal.ComputedDecorator;};
variable ComputedProperty
const ComputedProperty: typeof metal.ComputedProperty;
variable Container
const Container: typeof InternalContainer;
variable ContainerDebugAdapter
const ContainerDebugAdapter: typeof EmberContainerDebugAdapter;
variable Controller
const Controller: typeof EmberController;
variable controllerFor
const controllerFor: ( container: InternalContainer, controllerName: string, lookupOptions: RegisterOptions) => object | InternalFactory<object, FactoryClass>;
variable ControllerMixin
const ControllerMixin: EmberMixin;
variable CoreObject
const CoreObject: typeof EmberCoreObject;
variable DataAdapter
const DataAdapter: typeof EmberDataAdapter;
variable debug
const debug: EmberDebug.DebugFunc;
variable Debug
const Debug: { registerDeprecationHandler: ( handler: import('@ember/debug/lib/handlers').HandlerCallback<EmberDebug.DeprecationOptions> ) => void; registerWarnHandler: import('@ember/debug/lib/warn').RegisterHandlerFunc; isComputed: typeof metal.isComputed;};
variable defineProperty
const defineProperty: ( obj: object, keyName: string, desc?: PropertyDescriptor | metal.ExtendedMethodDecorator, data?: any, _meta?: Meta) => void;
variable deprecate
const deprecate: ( message: string, test?: boolean, options?: EmberDebug.DeprecationOptions) => void;
variable deprecateFunc
const deprecateFunc: EmberDebug.DeprecateFuncFunc;
variable destroy
const destroy: any;
variable endPropertyChanges
const endPropertyChanges: () => void;
variable Engine
const Engine: typeof EmberEngine;
variable EngineInstance
const EngineInstance: typeof EmberEngineInstance;
variable Enumerable
const Enumerable: EmberMixin;
variable ENV
const ENV: {};
variable EventDispatcher
const EventDispatcher: typeof views.EventDispatcher;
variable Evented
const Evented: EmberMixin;
variable expandProperties
const expandProperties: ( pattern: string, callback: (expansion: string) => void) => void;
variable FEATURES
const FEATURES: { isEnabled: typeof isEnabled };
variable generateController
const generateController: ( owner: Owner, controllerName: string) => EmberController<unknown>;
variable generateControllerFactory
const generateControllerFactory: ( owner: Owner, controllerName: string) => InternalFactory<{}, FactoryClass>;
variable generateGuid
const generateGuid: (obj: object, prefix?: string) => String;
variable get
const get: { <T extends object, K extends keyof T>(obj: T, keyName: K): T[K]; (obj: unknown, keyName: string): unknown;};
variable getProperties
const getProperties: { <T, K extends keyof T>(obj: T, list: K[]): Pick<T, K>; <T, K extends keyof T>(obj: T, ...list: K[]): Pick<T, K>; <K extends string>(obj: unknown, list: K[]): Record<K, unknown>; <K extends string>(obj: unknown, ...list: K[]): Record<K, unknown>;};
variable GUID_KEY
const GUID_KEY: string;
variable guidFor
const guidFor: (value: any) => string;
variable Handlebars
let Handlebars: EmberHandlebars;
variable HashLocation
const HashLocation: typeof EmberHashLocation;
variable hasListeners
const hasListeners: (obj: object, eventName: string) => boolean;
variable Helper
const Helper: typeof EmberHelper;
variable HistoryLocation
const HistoryLocation: typeof EmberHistoryLocation;
variable HTMLBars
let HTMLBars: EmberHTMLBars;
variable inspect
const inspect: (this: any, obj: any) => string;
variable instrument
const instrument: { <Result>(name: string, callback: InstrumentCallback<undefined, Result>): Result; <Binding, Result>( name: string, callback: InstrumentCallback<Binding, Result>, binding: Binding ): Result; <Result>( name: string, payload: object, callback: InstrumentCallback<undefined, Result> ): Result; <Binding, Result>( name: string, payload: object, callback: InstrumentCallback<Binding, Result>, binding: Binding ): Result;};
variable Instrumentation
const Instrumentation: { instrument: typeof instrumentation.instrument; subscribe: typeof instrumentation.subscribe; unsubscribe: typeof instrumentation.unsubscribe; reset: typeof instrumentation.reset;};
variable isArray
const isArray: (obj: unknown) => obj is EmberArray<unknown> | ArrayLike<unknown>;
variable isBlank
const isBlank: (obj: unknown) => boolean;
variable isEmpty
const isEmpty: (obj: unknown) => boolean;
variable isEqual
const isEqual: (a: unknown, b: unknown) => boolean;
variable isNamespace
const isNamespace: boolean;
variable isNone
const isNone: (obj: any) => obj is null;
variable isPresent
const isPresent: <T>(obj: T) => obj is T;
variable libraries
const libraries: metal.Libraries;
variable lookup
let lookup: Record<string, unknown>;
variable makeArray
const makeArray: <T, TT>(obj: T) => T extends TT[] ? T : T extends null ? [] : [T];
variable meta
const meta: { (obj: object): import('@ember/-internals/meta').Meta; _counters?: import('@ember/-internals/meta').MetaCounters | undefined;};
variable mixin
const mixin: (obj: object, ...args: any[]) => object;
variable Mixin
const Mixin: typeof EmberMixin;
variable MutableArray
const MutableArray: EmberMixin;
variable MutableEnumerable
const MutableEnumerable: EmberMixin;
variable Namespace
const Namespace: typeof EmberNamespace;
variable NativeArray
const NativeArray: EmberMixin;
variable NoneLocation
const NoneLocation: typeof EmberNoneLocation;
variable notifyPropertyChange
const notifyPropertyChange: ( obj: object, keyName: string, _meta?: Meta, value?: unknown) => void;
variable Object
const Object: typeof EmberObject;
variable ObjectProxy
const ObjectProxy: typeof EmberObjectProxy;
variable Observable
const Observable: EmberMixin;
variable observer
const observer: <T extends AnyFn>( ...args: | [propertyName: string, ...additionalPropertyNames: string[], func: T] | [ObserverDefinition<T>]) => T;
variable on
const on: <T extends AnyFn>(...args: [...eventNames: string[], func: T]) => T;
variable onerror
let onerror: (error: Error) => unknown;
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) { const payload = { stack: error.stack, otherInformation: 'whatever app state you want to provide' };
fetch('/report-error', { method: 'POST', body: JSON.stringify(payload) }); }; ```
Internally,
Ember.onerror
is used as Backburner's error handler.onerror Ember
Parameter error
the error object
Modifiers
@public
variable onLoad
const onLoad: (name: string, callback: (obj: any) => void) => void;
variable PromiseProxyMixin
const PromiseProxyMixin: EmberMixin;
variable Registry
const Registry: typeof InternalRegistry;
variable removeListener
const removeListener: ( obj: object, eventName: string, targetOrFunction: object | Function, functionOrName?: string | Function) => void;
variable removeObserver
const removeObserver: ( obj: any, path: string, target: object | Function, method?: string | Function, sync?: boolean) => void;
variable Route
const Route: typeof EmberRoute;
variable Router
const Router: typeof EmberRouter;
variable RouterDSL
const RouterDSL: typeof EmberRouterDSL;
variable run
const run: { <F extends () => any>(method: F): ReturnType<F>; <F extends AnyFn>(method: F, ...args: Parameters<F>): ReturnType<F>; <T, F extends (this: T, ...args: any[]) => any>( target: T, method: F, ...args: Parameters<F> ): ReturnType<F>; <T, U extends keyof T>( target: T, method: U, ...args: T[U] extends AnyFn ? Parameters<T[U]> : [] ): T[U] extends AnyFn ? ReturnType<T[U]> : unknown;};
variable runInDebug
const runInDebug: EmberDebug.RunInDebugFunc;
variable runLoadHooks
const runLoadHooks: (name: string, object: unknown) => void;
variable sendEvent
const sendEvent: ( obj: object, eventName: string, params?: any[], actions?: any[], _meta?: Meta) => boolean;
variable Service
const Service: typeof EmberService;
variable set
const set: <T>(obj: object, keyName: string, value: T, tolerant?: boolean) => T;
variable setOwner
const setOwner: (object: object, owner: Owner) => void;
variable setProperties
const setProperties: { <T, K extends keyof T>(obj: T, properties: Pick<T, K>): Pick<T, K>; <T extends Record<string, unknown>>(obj: object, properties: T): T;};
variable setupForTesting
let setupForTesting: () => void;
variable subscribe
const subscribe: <T>( pattern: string, object: instrumentation.Listener<T>) => instrumentation.Subscriber<T>;
variable TEMPLATES
let TEMPLATES: TemplatesRegistry;
Global hash of shared templates. This will automatically be populated by the build tools so that you can store your Handlebars templates in separate files that get loaded into JavaScript at buildtime.
TEMPLATES Ember Object
variable Test
let Test: { _helpers: Record<string, { method: AnyFn; meta: { wait: boolean } }>; registerHelper: ( name: string, helperMethod: (app: EmberApplication, ...args: any[]) => unknown ) => void; registerAsyncHelper: (name: string, helperMethod: AnyFn) => void; unregisterHelper: (name: string) => void; onInjectHelpers: (callback: (app: EmberApplication) => void) => void; Promise: typeof TestPromise; promise: <T>(resolver: Executor<T>, label?: string) => TestPromise<T>; resolve: (result: unknown, label?: string) => RSVP.default.Promise<unknown>; registerWaiter: { <T>(context: T, callback: (this: T) => unknown): void; (callback: (this: null) => unknown): void; }; unregisterWaiter: (context: unknown, callback: unknown) => void; checkWaiters: () => boolean;} & { Adapter: NonNullable<typeof EmberTestingImpl>['Adapter']; QUnitAdapter: NonNullable<typeof EmberTestingImpl>['QUnitAdapter'];};
variable testing
let testing: boolean;
variable trySet
const trySet: <T>(root: object, path: string, value: T) => T;
variable typeOf
const typeOf: (item: unknown) => TypeName;
variable uuid
const uuid: () => number;
variable VERSION
const VERSION: string;
The semantic version
VERSION String
Modifiers
@public
variable ViewUtils
const ViewUtils: { getChildViews: typeof views.getChildViews; getElementView: typeof views.getElementView; getRootViews: typeof views.getRootViews; getViewBounds: typeof views.getViewBounds; getViewBoundingClientRect: typeof views.getViewBoundingClientRect; getViewClientRects: typeof views.getViewClientRects; getViewElement: typeof views.getViewElement; isSimpleClick: typeof views.isSimpleClick; isSerializationFirstNode: any;};
variable warn
const warn: WarnFunc;
variable wrap
const wrap: (func: Function, superFunc: Function) => Function;
function A
A: <T>(arr?: T[]) => EmberNativeArray<T>;
function getOwner
getOwner: (object: object) => import('@ember/owner').default | undefined;
function inject
inject: typeof inject;
Namespace for injection helper methods.
inject Ember
Modifiers
@public
function toString
toString: () => string;
type ActionHandler
type ActionHandler = InternalActionHandler;
type Application
type Application = EmberApplication;
type ApplicationInstance
type ApplicationInstance = EmberApplicationInstance;
type Array
type Array<T> = EmberArray<T>;
type ArrayProxy
type ArrayProxy<T> = EmberArrayProxy<T>;
type Comparable
type Comparable = InternalComparable;
type Component
type Component<S = unknown> = EmberComponent<S>;
type ComputedProperty
type ComputedProperty = EmberComputedProperty;
type Container
type Container = InternalContainer;
type ContainerDebugAdapter
type ContainerDebugAdapter = EmberContainerDebugAdapter;
type Controller
type Controller<T = unknown> = EmberController<T>;
type ControllerMixin
type ControllerMixin<T> = EmberControllerMixin<T>;
type CoreObject
type CoreObject = EmberCoreObject;
type DataAdapter
type DataAdapter<T> = EmberDataAdapter<T>;
type Engine
type Engine = EmberEngine;
type EngineInstance
type EngineInstance = EmberEngineInstance;
type Enumerable
type Enumerable = EmberEnumerable;
type Evented
type Evented = EmberEvented;
type HashLocation
type HashLocation = EmberHashLocation;
type Helper
type Helper<S = unknown> = EmberHelper<S>;
type HistoryLocation
type HistoryLocation = EmberHistoryLocation;
type Mixin
type Mixin = EmberMixin;
type MutableArray
type MutableArray<T> = EmberMutableArray<T>;
type MutableEnumerable
type MutableEnumerable = EmberMutableEnumerable;
type Namespace
type Namespace = EmberNamespace;
type NativeArray
type NativeArray<T> = EmberNativeArray<T>;
type NoneLocation
type NoneLocation = EmberNoneLocation;
type Object
type Object = EmberObject;
type ObjectProxy
type ObjectProxy = EmberObjectProxy;
type Observable
type Observable = EmberObservable;
type PromiseProxyMixin
type PromiseProxyMixin<T> = EmberPromiseProxyMixin<T>;
type Registry
type Registry = InternalRegistry;
type Route
type Route = EmberRoute;
type Router
type Router = EmberRouter;
type RouterDSL
type RouterDSL = EmberRouterDSL;
type Service
type Service = EmberService;
namespace ember/barrel.Ember.inject
namespace ember/barrel.Ember.inject {}
variable controller
var controller: { (name: string): PropertyDecorator; (args_0: object, args_1: string): void; ( target: object, propertyName: string, descriptor?: PropertyDescriptor & { initializer?: any } ): PropertyDescriptor & { initializer?: any }; (): PropertyDecorator;};
variable service
var service: { (name: string): PropertyDecorator; (args_0: object, args_1: string): void; ( target: object, propertyName: string, descriptor?: PropertyDescriptor & { initializer?: any } ): PropertyDescriptor & { initializer?: any }; (): PropertyDecorator;};
namespace ember/version
module 'ember/version' {}
variable _default
const _default: string;
Package Files (327)
- types/stable/@ember/-internals/browser-environment/index.d.ts
- types/stable/@ember/-internals/browser-environment/lib/has-dom.d.ts
- types/stable/@ember/-internals/container/index.d.ts
- types/stable/@ember/-internals/container/lib/container.d.ts
- types/stable/@ember/-internals/container/lib/registry.d.ts
- types/stable/@ember/-internals/deprecations/index.d.ts
- types/stable/@ember/-internals/environment/index.d.ts
- types/stable/@ember/-internals/environment/lib/context.d.ts
- types/stable/@ember/-internals/environment/lib/env.d.ts
- types/stable/@ember/-internals/environment/lib/global.d.ts
- types/stable/@ember/-internals/error-handling/index.d.ts
- types/stable/@ember/-internals/glimmer/index.d.ts
- types/stable/@ember/-internals/glimmer/lib/component-managers/curly.d.ts
- types/stable/@ember/-internals/glimmer/lib/component-managers/mount.d.ts
- types/stable/@ember/-internals/glimmer/lib/component-managers/outlet.d.ts
- types/stable/@ember/-internals/glimmer/lib/component-managers/root.d.ts
- types/stable/@ember/-internals/glimmer/lib/component.d.ts
- types/stable/@ember/-internals/glimmer/lib/components/abstract-input.d.ts
- types/stable/@ember/-internals/glimmer/lib/components/input.d.ts
- types/stable/@ember/-internals/glimmer/lib/components/internal.d.ts
- types/stable/@ember/-internals/glimmer/lib/components/link-to.d.ts
- types/stable/@ember/-internals/glimmer/lib/components/textarea.d.ts
- types/stable/@ember/-internals/glimmer/lib/dom.d.ts
- types/stable/@ember/-internals/glimmer/lib/environment.d.ts
- types/stable/@ember/-internals/glimmer/lib/glimmer-tracking-docs.d.ts
- types/stable/@ember/-internals/glimmer/lib/helper.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/-disallow-dynamic-resolution.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/-in-element-null-check.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/-normalize-class.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/-resolve.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/-track-array.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/action.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/array.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/component.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/concat.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/each-in.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/fn.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/get.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/hash.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/helper.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/if-unless.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/internal-helper.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/log.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/modifier.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/mut.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/page-title.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/readonly.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/unbound.d.ts
- types/stable/@ember/-internals/glimmer/lib/helpers/unique-id.d.ts
- types/stable/@ember/-internals/glimmer/lib/modifiers/action.d.ts
- types/stable/@ember/-internals/glimmer/lib/modifiers/internal.d.ts
- types/stable/@ember/-internals/glimmer/lib/modifiers/on.d.ts
- types/stable/@ember/-internals/glimmer/lib/renderer.d.ts
- types/stable/@ember/-internals/glimmer/lib/resolver.d.ts
- types/stable/@ember/-internals/glimmer/lib/setup-registry.d.ts
- types/stable/@ember/-internals/glimmer/lib/syntax/in-element.d.ts
- types/stable/@ember/-internals/glimmer/lib/syntax/let.d.ts
- types/stable/@ember/-internals/glimmer/lib/syntax/mount.d.ts
- types/stable/@ember/-internals/glimmer/lib/syntax/outlet.d.ts
- types/stable/@ember/-internals/glimmer/lib/syntax/utils.d.ts
- types/stable/@ember/-internals/glimmer/lib/template.d.ts
- types/stable/@ember/-internals/glimmer/lib/template_registry.d.ts
- types/stable/@ember/-internals/glimmer/lib/templates/empty.d.ts
- types/stable/@ember/-internals/glimmer/lib/templates/input.d.ts
- types/stable/@ember/-internals/glimmer/lib/templates/link-to.d.ts
- types/stable/@ember/-internals/glimmer/lib/templates/outlet.d.ts
- types/stable/@ember/-internals/glimmer/lib/templates/root.d.ts
- types/stable/@ember/-internals/glimmer/lib/templates/textarea.d.ts
- types/stable/@ember/-internals/glimmer/lib/utils/bindings.d.ts
- types/stable/@ember/-internals/glimmer/lib/utils/curly-component-state-bucket.d.ts
- types/stable/@ember/-internals/glimmer/lib/utils/debug-render-message.d.ts
- types/stable/@ember/-internals/glimmer/lib/utils/iterator.d.ts
- types/stable/@ember/-internals/glimmer/lib/utils/managers.d.ts
- types/stable/@ember/-internals/glimmer/lib/utils/outlet.d.ts
- types/stable/@ember/-internals/glimmer/lib/utils/process-args.d.ts
- types/stable/@ember/-internals/glimmer/lib/utils/serialization-first-node-helpers.d.ts
- types/stable/@ember/-internals/glimmer/lib/utils/string.d.ts
- types/stable/@ember/-internals/glimmer/lib/utils/to-bool.d.ts
- types/stable/@ember/-internals/glimmer/lib/views/outlet.d.ts
- types/stable/@ember/-internals/meta/index.d.ts
- types/stable/@ember/-internals/meta/lib/meta.d.ts
- types/stable/@ember/-internals/metal/index.d.ts
- types/stable/@ember/-internals/metal/lib/alias.d.ts
- types/stable/@ember/-internals/metal/lib/array.d.ts
- types/stable/@ember/-internals/metal/lib/array_events.d.ts
- types/stable/@ember/-internals/metal/lib/cache.d.ts
- types/stable/@ember/-internals/metal/lib/cached.d.ts
- types/stable/@ember/-internals/metal/lib/chain-tags.d.ts
- types/stable/@ember/-internals/metal/lib/change_event.d.ts
- types/stable/@ember/-internals/metal/lib/computed.d.ts
- types/stable/@ember/-internals/metal/lib/computed_cache.d.ts
- types/stable/@ember/-internals/metal/lib/decorator.d.ts
- types/stable/@ember/-internals/metal/lib/dependent_keys.d.ts
- types/stable/@ember/-internals/metal/lib/deprecate_property.d.ts
- types/stable/@ember/-internals/metal/lib/each_proxy_events.d.ts
- types/stable/@ember/-internals/metal/lib/events.d.ts
- types/stable/@ember/-internals/metal/lib/expand_properties.d.ts
- types/stable/@ember/-internals/metal/lib/get_properties.d.ts
- types/stable/@ember/-internals/metal/lib/injected_property.d.ts
- types/stable/@ember/-internals/metal/lib/libraries.d.ts
- types/stable/@ember/-internals/metal/lib/namespace_search.d.ts
- types/stable/@ember/-internals/metal/lib/object-at.d.ts
- types/stable/@ember/-internals/metal/lib/observer.d.ts
- types/stable/@ember/-internals/metal/lib/path_cache.d.ts
- types/stable/@ember/-internals/metal/lib/properties.d.ts
- types/stable/@ember/-internals/metal/lib/property_events.d.ts
- types/stable/@ember/-internals/metal/lib/property_get.d.ts
- types/stable/@ember/-internals/metal/lib/property_set.d.ts
- types/stable/@ember/-internals/metal/lib/set_properties.d.ts
- types/stable/@ember/-internals/metal/lib/tags.d.ts
- types/stable/@ember/-internals/metal/lib/tracked.d.ts
- types/stable/@ember/-internals/owner/index.d.ts
- types/stable/@ember/-internals/routing/index.d.ts
- types/stable/@ember/-internals/runtime/index.d.ts
- types/stable/@ember/-internals/runtime/lib/ext/rsvp.d.ts
- types/stable/@ember/-internals/runtime/lib/mixins/-proxy.d.ts
- types/stable/@ember/-internals/runtime/lib/mixins/action_handler.d.ts
- types/stable/@ember/-internals/runtime/lib/mixins/comparable.d.ts
- types/stable/@ember/-internals/runtime/lib/mixins/container_proxy.d.ts
- types/stable/@ember/-internals/runtime/lib/mixins/registry_proxy.d.ts
- types/stable/@ember/-internals/runtime/lib/mixins/target_action_support.d.ts
- types/stable/@ember/-internals/string/index.d.ts
- types/stable/@ember/-internals/utility-types/index.d.ts
- types/stable/@ember/-internals/utils/index.d.ts
- types/stable/@ember/-internals/utils/lib/cache.d.ts
- types/stable/@ember/-internals/utils/lib/dictionary.d.ts
- types/stable/@ember/-internals/utils/lib/get-debug-name.d.ts
- types/stable/@ember/-internals/utils/lib/guid.d.ts
- types/stable/@ember/-internals/utils/lib/intern.d.ts
- types/stable/@ember/-internals/utils/lib/invoke.d.ts
- types/stable/@ember/-internals/utils/lib/is_proxy.d.ts
- types/stable/@ember/-internals/utils/lib/lookup-descriptor.d.ts
- types/stable/@ember/-internals/utils/lib/mandatory-setter.d.ts
- types/stable/@ember/-internals/utils/lib/name.d.ts
- types/stable/@ember/-internals/utils/lib/spec.d.ts
- types/stable/@ember/-internals/utils/lib/super.d.ts
- types/stable/@ember/-internals/utils/lib/symbol.d.ts
- types/stable/@ember/-internals/utils/lib/to-string.d.ts
- types/stable/@ember/-internals/views/index.d.ts
- types/stable/@ember/-internals/views/lib/compat/attrs.d.ts
- types/stable/@ember/-internals/views/lib/compat/fallback-view-registry.d.ts
- types/stable/@ember/-internals/views/lib/component_lookup.d.ts
- types/stable/@ember/-internals/views/lib/mixins/action_support.d.ts
- types/stable/@ember/-internals/views/lib/mixins/child_views_support.d.ts
- types/stable/@ember/-internals/views/lib/mixins/class_names_support.d.ts
- types/stable/@ember/-internals/views/lib/mixins/view_state_support.d.ts
- types/stable/@ember/-internals/views/lib/mixins/view_support.d.ts
- types/stable/@ember/-internals/views/lib/system/action_manager.d.ts
- types/stable/@ember/-internals/views/lib/system/event_dispatcher.d.ts
- types/stable/@ember/-internals/views/lib/system/utils.d.ts
- types/stable/@ember/-internals/views/lib/views/core_view.d.ts
- types/stable/@ember/-internals/views/lib/views/states.d.ts
- types/stable/@ember/application/index.d.ts
- types/stable/@ember/application/instance.d.ts
- types/stable/@ember/application/lib/lazy_load.d.ts
- types/stable/@ember/application/namespace.d.ts
- types/stable/@ember/array/-internals.d.ts
- types/stable/@ember/array/index.d.ts
- types/stable/@ember/array/lib/make-array.d.ts
- types/stable/@ember/array/make.d.ts
- types/stable/@ember/array/mutable.d.ts
- types/stable/@ember/array/proxy.d.ts
- types/stable/@ember/canary-features/index.d.ts
- types/stable/@ember/component/helper.d.ts
- types/stable/@ember/component/index.d.ts
- types/stable/@ember/component/template-only.d.ts
- types/stable/@ember/controller/index.d.ts
- types/stable/@ember/debug/container-debug-adapter.d.ts
- types/stable/@ember/debug/data-adapter.d.ts
- types/stable/@ember/debug/index.d.ts
- types/stable/@ember/debug/lib/assert.d.ts
- types/stable/@ember/debug/lib/capture-render-tree.d.ts
- types/stable/@ember/debug/lib/deprecate.d.ts
- types/stable/@ember/debug/lib/handlers.d.ts
- types/stable/@ember/debug/lib/inspect.d.ts
- types/stable/@ember/debug/lib/testing.d.ts
- types/stable/@ember/debug/lib/warn.d.ts
- types/stable/@ember/deprecated-features/index.d.ts
- types/stable/@ember/destroyable/index.d.ts
- types/stable/@ember/engine/index.d.ts
- types/stable/@ember/engine/instance.d.ts
- types/stable/@ember/engine/lib/engine-parent.d.ts
- types/stable/@ember/engine/parent.d.ts
- types/stable/@ember/enumerable/index.d.ts
- types/stable/@ember/enumerable/mutable.d.ts
- types/stable/@ember/helper/index.d.ts
- types/stable/@ember/instrumentation/index.d.ts
- types/stable/@ember/modifier/index.d.ts
- types/stable/@ember/modifier/on.d.ts
- types/stable/@ember/object/-internals.d.ts
- types/stable/@ember/object/compat.d.ts
- types/stable/@ember/object/computed.d.ts
- types/stable/@ember/object/core.d.ts
- types/stable/@ember/object/evented.d.ts
- types/stable/@ember/object/events.d.ts
- types/stable/@ember/object/index.d.ts
- types/stable/@ember/object/internals.d.ts
- types/stable/@ember/object/lib/computed/computed_macros.d.ts
- types/stable/@ember/object/lib/computed/reduce_computed_macros.d.ts
- types/stable/@ember/object/mixin.d.ts
- types/stable/@ember/object/observable.d.ts
- types/stable/@ember/object/observers.d.ts
- types/stable/@ember/object/promise-proxy-mixin.d.ts
- types/stable/@ember/object/proxy.d.ts
- types/stable/@ember/owner/index.d.ts
- types/stable/@ember/renderer/index.d.ts
- types/stable/@ember/routing/-internals.d.ts
- types/stable/@ember/routing/hash-location.d.ts
- types/stable/@ember/routing/history-location.d.ts
- types/stable/@ember/routing/index.d.ts
- types/stable/@ember/routing/lib/cache.d.ts
- types/stable/@ember/routing/lib/controller_for.d.ts
- types/stable/@ember/routing/lib/dsl.d.ts
- types/stable/@ember/routing/lib/engines.d.ts
- types/stable/@ember/routing/lib/generate_controller.d.ts
- types/stable/@ember/routing/lib/location-utils.d.ts
- types/stable/@ember/routing/lib/query_params.d.ts
- types/stable/@ember/routing/lib/route-info.d.ts
- types/stable/@ember/routing/lib/router_state.d.ts
- types/stable/@ember/routing/lib/routing-service.d.ts
- types/stable/@ember/routing/lib/utils.d.ts
- types/stable/@ember/routing/location.d.ts
- types/stable/@ember/routing/none-location.d.ts
- types/stable/@ember/routing/route-info.d.ts
- types/stable/@ember/routing/route.d.ts
- types/stable/@ember/routing/router-service.d.ts
- types/stable/@ember/routing/router.d.ts
- types/stable/@ember/routing/transition.d.ts
- types/stable/@ember/runloop/-private/backburner.d.ts
- types/stable/@ember/runloop/index.d.ts
- types/stable/@ember/service/index.d.ts
- types/stable/@ember/template-compilation/index.d.ts
- types/stable/@ember/template-compiler/-internal-primitives.d.ts
- types/stable/@ember/template-compiler/-internal-utils.d.ts
- types/stable/@ember/template-compiler/index.d.ts
- types/stable/@ember/template-compiler/lib/-internal/primitives.d.ts
- types/stable/@ember/template-compiler/lib/compile-options.d.ts
- types/stable/@ember/template-compiler/lib/dasherize-component-name.d.ts
- types/stable/@ember/template-compiler/lib/plugins/assert-against-attrs.d.ts
- types/stable/@ember/template-compiler/lib/plugins/assert-against-named-outlets.d.ts
- types/stable/@ember/template-compiler/lib/plugins/assert-input-helper-without-block.d.ts
- types/stable/@ember/template-compiler/lib/plugins/assert-reserved-named-arguments.d.ts
- types/stable/@ember/template-compiler/lib/plugins/index.d.ts
- types/stable/@ember/template-compiler/lib/plugins/transform-action-syntax.d.ts
- types/stable/@ember/template-compiler/lib/plugins/transform-each-in-into-each.d.ts
- types/stable/@ember/template-compiler/lib/plugins/transform-each-track-array.d.ts
- types/stable/@ember/template-compiler/lib/plugins/transform-in-element.d.ts
- types/stable/@ember/template-compiler/lib/plugins/transform-quoted-bindings-into-just-bindings.d.ts
- types/stable/@ember/template-compiler/lib/plugins/transform-resolutions.d.ts
- types/stable/@ember/template-compiler/lib/plugins/transform-wrap-mount-and-outlet.d.ts
- types/stable/@ember/template-compiler/lib/plugins/utils.d.ts
- types/stable/@ember/template-compiler/lib/public-api.d.ts
- types/stable/@ember/template-compiler/lib/public-types.d.ts
- types/stable/@ember/template-compiler/lib/runtime.d.ts
- types/stable/@ember/template-compiler/lib/system/calculate-location-display.d.ts
- types/stable/@ember/template-compiler/lib/template.d.ts
- types/stable/@ember/template-compiler/lib/types.d.ts
- types/stable/@ember/template-compiler/runtime.d.ts
- types/stable/@ember/template-factory/index.d.ts
- types/stable/@ember/template/index.d.ts
- types/stable/@ember/test/adapter.d.ts
- types/stable/@ember/test/index.d.ts
- types/stable/@ember/utils/index.d.ts
- types/stable/@ember/utils/lib/compare.d.ts
- types/stable/@ember/utils/lib/is-equal.d.ts
- types/stable/@ember/utils/lib/is_blank.d.ts
- types/stable/@ember/utils/lib/is_empty.d.ts
- types/stable/@ember/utils/lib/is_none.d.ts
- types/stable/@ember/utils/lib/is_present.d.ts
- types/stable/@ember/utils/lib/type-of.d.ts
- types/stable/@ember/version/index.d.ts
- types/stable/@glimmer/tracking/index.d.ts
- types/stable/@glimmer/tracking/primitives/cache.d.ts
- types/stable/ember-template-compiler/index.d.ts
- types/stable/ember-template-compiler/lib/-internal.d.ts
- types/stable/ember-template-compiler/lib/plugins/assert-against-attrs.d.ts
- types/stable/ember-template-compiler/lib/plugins/assert-against-named-outlets.d.ts
- types/stable/ember-template-compiler/lib/plugins/assert-input-helper-without-block.d.ts
- types/stable/ember-template-compiler/lib/plugins/assert-reserved-named-arguments.d.ts
- types/stable/ember-template-compiler/lib/plugins/index.d.ts
- types/stable/ember-template-compiler/lib/plugins/transform-action-syntax.d.ts
- types/stable/ember-template-compiler/lib/plugins/transform-each-in-into-each.d.ts
- types/stable/ember-template-compiler/lib/plugins/transform-each-track-array.d.ts
- types/stable/ember-template-compiler/lib/plugins/transform-in-element.d.ts
- types/stable/ember-template-compiler/lib/plugins/transform-quoted-bindings-into-just-bindings.d.ts
- types/stable/ember-template-compiler/lib/plugins/transform-resolutions.d.ts
- types/stable/ember-template-compiler/lib/plugins/transform-wrap-mount-and-outlet.d.ts
- types/stable/ember-template-compiler/lib/plugins/utils.d.ts
- types/stable/ember-template-compiler/lib/public-api.d.ts
- types/stable/ember-template-compiler/lib/system/bootstrap.d.ts
- types/stable/ember-template-compiler/lib/system/calculate-location-display.d.ts
- types/stable/ember-template-compiler/lib/system/compile-options.d.ts
- types/stable/ember-template-compiler/lib/system/compile.d.ts
- types/stable/ember-template-compiler/lib/system/dasherize-component-name.d.ts
- types/stable/ember-template-compiler/lib/system/initializer.d.ts
- types/stable/ember-template-compiler/lib/system/precompile.d.ts
- types/stable/ember-template-compiler/lib/types.d.ts
- types/stable/ember-template-compiler/minimal.d.ts
- types/stable/ember-testing/index.d.ts
- types/stable/ember-testing/lib/adapters/adapter.d.ts
- types/stable/ember-testing/lib/adapters/qunit.d.ts
- types/stable/ember-testing/lib/ext/application.d.ts
- types/stable/ember-testing/lib/ext/rsvp.d.ts
- types/stable/ember-testing/lib/helpers.d.ts
- types/stable/ember-testing/lib/helpers/and_then.d.ts
- types/stable/ember-testing/lib/helpers/current_path.d.ts
- types/stable/ember-testing/lib/helpers/current_route_name.d.ts
- types/stable/ember-testing/lib/helpers/current_url.d.ts
- types/stable/ember-testing/lib/helpers/pause_test.d.ts
- types/stable/ember-testing/lib/helpers/visit.d.ts
- types/stable/ember-testing/lib/helpers/wait.d.ts
- types/stable/ember-testing/lib/initializers.d.ts
- types/stable/ember-testing/lib/public-api.d.ts
- types/stable/ember-testing/lib/setup_for_testing.d.ts
- types/stable/ember-testing/lib/test.d.ts
- types/stable/ember-testing/lib/test/adapter.d.ts
- types/stable/ember-testing/lib/test/helpers.d.ts
- types/stable/ember-testing/lib/test/on_inject_helpers.d.ts
- types/stable/ember-testing/lib/test/pending_requests.d.ts
- types/stable/ember-testing/lib/test/promise.d.ts
- types/stable/ember-testing/lib/test/run.d.ts
- types/stable/ember-testing/lib/test/waiters.d.ts
- types/stable/ember/barrel.d.ts
- types/stable/ember/index.d.ts
- types/stable/ember/version.d.ts
- types/stable/index.d.ts
- types/stable/loader/lib/index.d.ts
Dependencies (42)
- @babel/core
- @ember/edition-utils
- @embroider/addon-shim
- @glimmer/compiler
- @glimmer/destroyable
- @glimmer/env
- @glimmer/global-context
- @glimmer/interfaces
- @glimmer/manager
- @glimmer/node
- @glimmer/opcode-compiler
- @glimmer/owner
- @glimmer/program
- @glimmer/reference
- @glimmer/runtime
- @glimmer/syntax
- @glimmer/util
- @glimmer/validator
- @glimmer/vm
- @glimmer/vm-babel-plugins
- @simple-dom/interface
- backburner.js
- broccoli-file-creator
- broccoli-funnel
- broccoli-merge-trees
- chalk
- ember-auto-import
- ember-cli-babel
- ember-cli-get-component-path-option
- ember-cli-is-package-missing
- ember-cli-normalize-entity-name
- ember-cli-path-utils
- ember-cli-string-utils
- ember-cli-typescript-blueprint-polyfill
- ember-cli-version-checker
- ember-router-generator
- inflection
- route-recognizer
- router_js
- semver
- silent-error
- simple-html-tokenizer
Dev Dependencies (57)
- @aws-sdk/client-s3
- @babel/plugin-transform-typescript
- @babel/preset-env
- @babel/types
- @embroider/shared-internals
- @glimmer/component
- @rollup/plugin-babel
- @simple-dom/document
- @swc-node/register
- @swc/core
- @tsconfig/ember
- @types/qunit
- @types/rsvp
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- ast-types
- auto-dist-tag
- babel-plugin-debug-macros
- babel-plugin-ember-template-compilation
- dag-map
- decorator-transforms
- ember-cli
- ember-cli-blueprint-test-helpers
- ember-cli-browserstack
- ember-cli-dependency-checker
- ember-cli-yuidoc
- eslint
- eslint-config-prettier
- eslint-import-resolver-node
- eslint-plugin-disable-features
- eslint-plugin-ember-internal
- eslint-plugin-import
- eslint-plugin-n
- eslint-plugin-prettier
- eslint-plugin-qunit
- execa
- expect-type
- finalhandler
- fs-extra
- git-repo-info
- github
- glob
- html-differ
- mocha
- npm-run-all2
- prettier
- puppeteer
- qunit
- recast
- rollup
- rsvp
- serve-static
- simple-dom
- testem
- testem-failure-only-reporter
- typescript
- vite
Peer Dependencies (1)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/ember-source
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/ember-source)
- HTML<a href="https://www.jsdocs.io/package/ember-source"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 26060 ms. - Missing or incorrect documentation? Open an issue for this package.