Template
A basic Template class. It renders a DOM HTML element or text from a definition and supports element attributes, children, bindings to observables and DOM event propagation.
A simple template can look like this:
const bind = Template.bind( observable, emitter );
new Template( {
tag: 'p',
attributes: {
class: 'foo',
style: {
backgroundColor: 'yellow'
}
},
on: {
click: bind.to( 'clicked' )
},
children: [
'A paragraph.'
]
} ).render();
and it will render the following HTML element:
<p class="foo" style="background-color: yellow;">A paragraph.</p>
Additionally, the observable will always fire clicked upon clicking <p> in the DOM.
See TemplateDefinition to know more about templates and complex template definitions.
Properties
attributes : Record<string, AttributeValues> | undefinedmodule:ui/template~Template#attributesThe attributes of the template, e.g.
{ id: [ 'ck-id' ] }, corresponding with the attributes of an HTML element.Note: This property only makes sense when
tagis defined.children : Array<Node | View<HTMLElement> | Template | ViewCollection<View<HTMLElement>>> | undefinedmodule:ui/template~Template#childreneventListeners : Record<string, Array<TemplateToBinding>> | undefinedmodule:ui/template~Template#eventListenersThe DOM event listeners of the template.
ns : string | undefinedmodule:ui/template~Template#nstag : string | undefinedmodule:ui/template~Template#tagThe tag (
tagName) of this template, e.g.div. It also indicates that the template renders to an HTML element.text : Array<TemplateSimpleValue | TemplateBinding> | undefinedmodule:ui/template~Template#textThe text of the template. It also indicates that the template renders to a DOM text node.
_isRendered : booleanprivatemodule:ui/template~Template#_isRenderedIndicates whether this particular Template instance has been rendered.
_revertData : null | RevertDataprivatemodule:ui/template~Template#_revertData
Methods
constructor( def )module:ui/template~Template#constructorCreates an instance of the
Templateclass.Parameters
def : TemplateDefinitionThe definition of the template.
apply( node ) → HTMLElement | Textmodule:ui/template~Template#applyApplies the template to an existing DOM Node, either HTML element or text.
Note: No new DOM nodes will be created. Applying extends:
attributes, event listeners, and
textContentof children only.Note: Existing
classandstyleattributes are extended when a template is applied to an HTML element, while other attributes andtextContentare overridden.Note: The process of applying a template can be easily reverted using the
revertmethod.const element = document.createElement( 'div' ); const observable = new Model( { divClass: 'my-div' } ); const emitter = Object.create( EmitterMixin ); const bind = Template.bind( observable, emitter ); new Template( { attributes: { id: 'first-div', class: bind.to( 'divClass' ) }, on: { click: bind( 'elementClicked' ) // Will be fired by the observable. }, children: [ 'Div text.' ] } ).apply( element ); console.log( element.outerHTML ); // -> '<div id="first-div" class="my-div"></div>'Copy codeParameters
node : HTMLElement | TextRoot node for the template to apply.
Returns
HTMLElement | Text
Related:
delegate( events ) → EmitterMixinDelegateChaininheritedmodule:ui/template~Template#delegateDelegates selected events to another
Emitter. For instance:emitterA.delegate( 'eventX' ).to( emitterB ); emitterA.delegate( 'eventX', 'eventY' ).to( emitterC );Copy codethen
eventXis delegated (fired by)emitterBandemitterCalong withdata:emitterA.fire( 'eventX', data );Copy codeand
eventYis delegated (fired by)emitterCalong withdata:emitterA.fire( 'eventY', data );Copy codeParameters
events : Array<string>Event names that will be delegated to another emitter.
Returns
fire( eventOrInfo, args ) → GetEventInfo<TEvent>[ 'return' ]inheritedmodule:ui/template~Template#fireFires an event, executing all callbacks registered for it.
The first parameter passed to callbacks is an
EventInfoobject, followed by the optionalargsprovided in thefire()method call.Type parameters
Parameters
eventOrInfo : GetNameOrEventInfo<TEvent>The name of the event or
EventInfoobject if event is delegated.args : TEvent[ 'args' ]Additional arguments to be passed to the callbacks.
Returns
GetEventInfo<TEvent>[ 'return' ]By default the method returns
undefined. However, the return value can be changed by listeners through modification of theevt.return's property (the event info is the first param of every callback).
module:ui/template~Template#getViewsReturns an iterator which traverses the template in search of
Viewinstances and returns them one by one.const viewFoo = new View(); const viewBar = new View(); const viewBaz = new View(); const template = new Template( { tag: 'div', children: [ viewFoo, { tag: 'div', children: [ viewBar ] }, viewBaz ] } ); // Logs: viewFoo, viewBar, viewBaz for ( const view of template.getViews() ) { console.log( view ); }Copy codeReturns
IterableIterator<View<HTMLElement>>
listenTo( emitter, event, callback, [ options ] ) → voidinheritedmodule:ui/template~Template#listenTo:BASE_EMITTERRegisters a callback function to be executed when an event is fired in a specific (emitter) object.
Events can be grouped in namespaces using
:. When namespaced event is fired, it additionally fires all callbacks for that namespace.// myEmitter.on( ... ) is a shorthand for myEmitter.listenTo( myEmitter, ... ). myEmitter.on( 'myGroup', genericCallback ); myEmitter.on( 'myGroup:myEvent', specificCallback ); // genericCallback is fired. myEmitter.fire( 'myGroup' ); // both genericCallback and specificCallback are fired. myEmitter.fire( 'myGroup:myEvent' ); // genericCallback is fired even though there are no callbacks for "foo". myEmitter.fire( 'myGroup:foo' );Copy codeAn event callback can stop the event and set the return value of the
firemethod.Type parameters
Parameters
emitter : EmitterThe object that fires the event.
event : TEvent[ 'name' ]The name of the event.
callback : GetCallback<TEvent>The function to be called on event.
[ options ] : GetCallbackOptions<TEvent>Additional options.
Returns
void
off( event, callback ) → voidinheritedmodule:ui/template~Template#offStops executing the callback on the given event. Shorthand for
this.stopListening( this, event, callback ).Parameters
event : stringThe name of the event.
callback : FunctionThe function to stop being called.
Returns
void
on( event, callback, [ options ] ) → voidinheritedmodule:ui/template~Template#onRegisters a callback function to be executed when an event is fired.
Shorthand for
this.listenTo( this, event, callback, options )(it makes the emitter listen on itself).Type parameters
Parameters
event : TEvent[ 'name' ]The name of the event.
callback : GetCallback<TEvent>The function to be called on event.
[ options ] : GetCallbackOptions<TEvent>Additional options.
Returns
void
once( event, callback, [ options ] ) → voidinheritedmodule:ui/template~Template#onceRegisters a callback function to be executed on the next time the event is fired only. This is similar to calling
onfollowed byoffin the callback.Type parameters
Parameters
event : TEvent[ 'name' ]The name of the event.
callback : GetCallback<TEvent>The function to be called on event.
[ options ] : GetCallbackOptions<TEvent>Additional options.
Returns
void
render() → HTMLElement | Textmodule:ui/template~Template#renderRenders a DOM Node (an HTML element or text) out of the template.
const domNode = new Template( { ... } ).render();Copy codeSee:
apply.Returns
HTMLElement | Text
revert( node ) → voidmodule:ui/template~Template#revertstopDelegating( [ event ], [ emitter ] ) → voidinheritedmodule:ui/template~Template#stopDelegatingStops delegating events. It can be used at different levels:
- To stop delegating all events.
- To stop delegating a specific event to all emitters.
- To stop delegating a specific event to a specific emitter.
Parameters
[ event ] : stringThe name of the event to stop delegating. If omitted, stops it all delegations.
[ emitter ] : Emitter(requires
event) The object to stop delegating a particular event to. If omitted, stops delegation ofeventto all emitters.
Returns
void
stopListening( [ emitter ], [ event ], [ callback ] ) → voidinheritedmodule:ui/template~Template#stopListening:BASE_STOPStops listening for events. It can be used at different levels:
- To stop listening to a specific callback.
- To stop listening to a specific event.
- To stop listening to all events fired by a specific object.
- To stop listening to all events fired by all objects.
Parameters
[ emitter ] : EmitterThe object to stop listening to. If omitted, stops it for all objects.
[ event ] : string(Requires the
emitter) The name of the event to stop listening to. If omitted, stops it for all events fromemitter.[ callback ] : Function(Requires the
event) The function to be removed from the call list for the givenevent.
Returns
void
_bindToObservable( options = { options.data, options.schema, options.updater } ) → voidprivatemodule:ui/template~Template#_bindToObservableFor a given
TemplateValueSchemacontainingTemplateBindingactivates the binding and sets its initial value.Note:
TemplateValueSchemacan be for HTML element attributes or text nodetextContent.Parameters
options : objectBinding options.
Propertiesoptions.data : RenderDataRendering data.
options.schema : Array<TemplateSimpleValue | TemplateBinding>options.updater : UpdaterA function which updates the DOM (like attribute or text).
Returns
void
_renderAttributes( data ) → voidprivatemodule:ui/template~Template#_renderAttributesRenders HTML element attributes out of
attributes.Parameters
data : RenderDataRendering data.
Returns
void
_renderElement( data ) → HTMLElement | Textprivatemodule:ui/template~Template#_renderElementRenders an HTML element out of the template.
Parameters
data : RenderDataRendering data.
Returns
HTMLElement | Text
_renderElementChildren( data ) → voidprivatemodule:ui/template~Template#_renderElementChildrenRecursively renders HTML element's children from
children.Parameters
data : RenderDataRendering data.
Returns
void
_renderNode( data ) → HTMLElement | Textprivatemodule:ui/template~Template#_renderNodeRenders a DOM Node (either an HTML element or text) out of the template.
Parameters
data : RenderDataRendering data.
Returns
HTMLElement | Text
_renderStyleAttribute( styles, data ) → voidprivatemodule:ui/template~Template#_renderStyleAttributeRenders the
styleattribute of an HTML element based onattributes.A style attribute is an object with static values:
attributes: { style: { color: 'red', '--color': 'red' } }Copy codeor values bound to
UIModelproperties:attributes: { style: { color: bind.to( ... ), '--color': bind.to( ... ) } }Copy codeNote: The
styleattribute is rendered without setting the namespace. It does not seem to be needed.Parameters
styles : Record<string, TemplateSimpleValue | TemplateBinding>Styles located in
attributes.styleofTemplateDefinition.data : RenderDataRendering data.
Returns
void
_renderText( data ) → HTMLElement | Textprivatemodule:ui/template~Template#_renderText_revertTemplateFromNode( node, revertData ) → voidprivatemodule:ui/template~Template#_revertTemplateFromNodeReverts template data from a node to return it to the original state.
Parameters
node : HTMLElement | TextA node to be reverted.
revertData : RevertDataAn object that stores information about what changes have been made by
applyto the node. SeerevertDatafor more information.
Returns
void
_setUpListeners( data ) → voidprivatemodule:ui/template~Template#_setUpListenersActivates
onevent listeners from theTemplateDefinitionon an HTML element.Parameters
data : RenderDataRendering data.
Returns
void
Static methods
module:ui/template~Template.bindAn entry point to the interface which binds DOM nodes to observables. There are two types of bindings:
- HTML element attributes or text
textContentsynchronized with attributes of anObservable. Learn more abouttoandif.
const bind = Template.bind( observable, emitter ); new Template( { attributes: { // Binds the element "class" attribute to observable#classAttribute. class: bind.to( 'classAttribute' ) } } ).render();Copy code- DOM events fired on HTML element propagated through
Observable. Learn more aboutto.
const bind = Template.bind( observable, emitter ); new Template( { on: { // Will be fired by the observable. click: bind( 'elementClicked' ) } } ).render();Copy codeAlso see
bindTemplate.Type parameters
TObservable : extends Observable
Parameters
observable : TObservableAn observable which provides boundable attributes.
emitter : EmitterAn emitter that listens to observable attribute changes or DOM Events (depending on the kind of the binding). Usually, a
Viewinstance.
Returns
BindChain<TObservable>
- HTML element attributes or text
extend( template, def ) → voidstaticmodule:ui/template~Template.extendExtends an existing
Templateinstance with some additional content from anotherTemplateDefinition.const bind = Template.bind( observable, emitter ); const template = new Template( { tag: 'p', attributes: { class: 'a', data-x: bind.to( 'foo' ) }, children: [ { tag: 'span', attributes: { class: 'b' }, children: [ 'Span' ] } ] } ); // Instance-level extension. Template.extend( template, { attributes: { class: 'b', data-x: bind.to( 'bar' ) }, children: [ { attributes: { class: 'c' } } ] } ); // Child extension. Template.extend( template.children[ 0 ], { attributes: { class: 'd' } } );Copy codethe
outerHTMLoftemplate.render()is:<p class="a b" data-x="{ observable.foo } { observable.bar }"> <span class="b c d">Span</span> </p>Copy codeParameters
template : TemplateAn existing template instance to be extended.
def : Partial<TemplateDefinition>Additional definition to be applied to a template.
Returns
void