Pasar parámetros con EventEmitter


Tengo una directiva para inicializar un jQueryUI sortable en un elemento DOM. El jQueryUI sortable también tiene un conjunto de eventos de devolución de llamada que se activan en ciertas acciones. Por ejemplo, cuando iniciao detiene elementos de ordenación.

Me gustaría pasar los parámetros de retorno de tal evento a través de la función emit(), para que pueda ver lo que sucede en mi función de devolución de llamada. Simplemente no he encontrado una manera de pasar parámetros a través de un EventEmiiter.

Actualmente tengo lo siguiente.

Mi directiva:

@Directive({
    selector: '[sortable]'
})
export class Sortable {
    @Output() stopSort = new EventEmitter();

    constructor(el: ElementRef) {
      console.log('directive');
        var options = {
          stop: (event, ui) => {
            this.stopSort.emit(); // How to pass the params event and ui...?
          }
        };

        $(el.nativeElement).sortable(options).disableSelection();
    }
}

Y este es mi Component que usa el evento emitido por la directiva:

@Component({
  selector: 'my-app',
  directives: [Sortable],
  providers: [],
  template: `
    <div>
      <h2>Event from jQueryUI to Component demo</h2>

      <ul id="sortable" sortable (stopSort)="stopSort(event, ui)">
        <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 1</li>
        <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 2</li>
        <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 3</li>
      </ul>
    </div>
  `
})
export class App {
  constructor() {

  }

  stopSort(event, ui) { // How do I get the 'event' and 'ui' params here?
    console.log('STOP SORT!', event);
  }
}

¿Cómo puedo obtener los parámetros event y ui en mi función stopSort()?

Aquí está una demostración de lo que tengo hasta ahora: http://plnkr.co/edit/5ACcetgwWWgTsKs1kWrA?p=info

Author: Frederik Struck-Schøning, 2016-02-14

4 answers

EventEmitter admite un argumento, que se pasa como $event a su controlador de eventos.

Envuelve tus parámetros en un objeto event cuando lo pasas a emit:

this.stopSort.emit({ event:event, ui: ui });

Luego, cuando manejes el evento, usa $event:

stopSort($event) { 
  alert('event param from Component: ' +$event.event);
  alert('ui param from Component: ' + $event.ui);
}

Demo Plnkr

 77
Author: pixelbits,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-26 13:56:23

La respuesta de Pixelbits ha cambiado un poco con la versión final. Si tiene varios parámetros, simplemente páselos como un objeto.

Componente secundario:

this.stopSort.emit({event,ui});

@Output() stopSort= new EventEmitter<any>();

Componente principal:

hereIsHeight(value) {
        console.log("Height = " + value.event); 
        console.log("Title = " + value.ui); 
    }   

HTML en el componente padre:

<test-child1 (stopSort)="hereIsHeight($event)"></test-child1>

Also También si tienes valores como: (con el "esto" delante)

this.stopSort.emit({this.event,this.ui});

No funcionarán, necesitas cambiarlos a otra cosa y luego pasar como:

let val1 = this.event;
let val2 = this.ui;
this.stopSort.emit({val1,val2});

*Actualización: Lea la respuesta de Collin B a continuación para una forma de pasar valores con " esto."

 9
Author: Alfa Bravo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-01 20:34:46

No puedo agregar un comentario, pero solo quería señalar de la respuesta de Alpha Bravo que puede pasar this.event, simplemente no puede usar la abreviatura de valor de propiedad:

this.stopSort.emit({ event : this.event, ui : this.ui });


También tenga en cuenta, si se pasan a través del EventEmmiter como this.stopSort.emit({ val1, val2 }); entonces se accederá a ellos en el padre como:

hereIsHeight(value) {
    console.log(`event = ${ value.val1 }`); 
    console.log(`ui = ${ value.val2 }`); 
}

Así que evitar la taquigrafía podría ser preferible en este tipo de situación para mantener la coherencia de los nombres.

 2
Author: Colin B.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-07 22:14:03

Funciona así en child:

@Output() myEvent: EventEmitter<boolean> = new EventEmitter();
myFunc(value: boolean) {
this.myEvent.emit(value);
}

Ahora solo tienes que agarrar el evento en el padre!

 2
Author: Ignacio Peletier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-05 06:29:53