import { IDirective , IComponent } from '../types' ; import { isFromVM , getVMVal } from '../compile' ; import { addHostBinding } from './host-binding' ; export param { ( IComponent | IDirective ) } instance returns { void } export function addHostListener ( instance ) { if ( ! instance . $hostListenerList ) return ; instance . $hostListenerList . forEach ( listener => { listener . handler = ( event ) => { const handlerArgs = [ ] ; if ( listener . args ) { listener . args . forEach ( arg => { if ( arg === '' ) return handlerArgs . push ( '' ) ; if ( arg === '$element' ) return handlerArgs . push ( instance . $nativeElement ) ; if ( arg === '$event' ) return handlerArgs . push ( event ) ; if ( /^\$event\.+/ . test ( arg ) ) return handlerArgs . push ( getVMVal ( event , arg . replace ( /^\$event\./ , '' ) ) ) ; if ( arg === 'true' || arg === 'false' ) return handlerArgs . push ( arg === 'true' ) ; if ( arg === 'null' ) return handlerArgs . push ( null ) ; if ( arg === 'undefined' ) return handlerArgs . push ( undefined ) ; if ( /^\'.*\'$/ . test ( arg ) || /^\".*\"$/ . test ( arg ) ) return arg ; if ( /(^[-,+]?\d+$)|(^[-, +]?\d+\.\d+$)/ . test ( arg ) ) return Number ( arg ) ; if ( isFromVM ( instance , arg ) ) return handlerArgs . push ( getVMVal ( instance , arg ) ) ; } ) ; } instance [ listener . propertyName ] . apply ( instance , handlerArgs ) ; if ( ( instance . constructor as any ) . nvType === 'nvDirective' ) addHostBinding ( instance ) ; } ; instance . $indivInstance . getRenderer . addEventListener ( instance . $nativeElement , listener . eventName , listener . handler ) ; } ) ; } export param { ( IComponent | IDirective ) } instance returns { void } export function removeHostListener ( instance ) { if ( ! instance . $hostListenerList || ! instance . $nativeElement ) return ; instance . $hostListenerList . forEach ( listener => { instance . $indivInstance . getRenderer . removeEventListener ( instance . $nativeElement , listener . eventName , listener . handler ) ; } ) ; } HostListener export param { string } eventName param { string [ ] } args returns { ( ( target : IComponent | IDirective , propertyName : string ) => any ) } export function HostListener ( eventName , args ? ) { return function ( target , propertyName ) : any { if ( ! target . $hostListenerList ) target . $hostListenerList = [ ] ; target . $hostListenerList . push ( { eventName , propertyName , args : args || [ ] , handler : null } ) ; return target [ propertyName ] ; } ; }