Pass parameters with EventEmitter

Vivendi picture Vivendi · Feb 14, 2016 · Viewed 86.5k times · Source

I have a directive to initializes a jQueryUI sortable on a DOM element. The jQueryUI sortable also has a set of callback events that trigger on certain actions. For example, when you start or stop sorting elements.

I'd like to pass the return parameters from such an event through the emit() function, so I can actually see what happend in my callback function. I just haven't found a way to pass parameters through an EventEmiiter.

I currently have the following.

My directive:

@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();
    }
}

And this is my Component that uses the event emiited by the directive:

@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);
  }
}

How can I get the event and ui params in my stopSort() function?

Here is a demo of what I have so far: http://plnkr.co/edit/5ACcetgwWWgTsKs1kWrA?p=info

Answer

pixelbits picture pixelbits · Feb 14, 2016

EventEmitter supports one argument, which is passed as $event to your event handler.

Wrap your parameters in an event object when you pass it to emit:

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

Then, when you handle the event, use $event:

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

Demo Plnkr