我有一个指令来初始化DOM元素上的jQueryUI可排序。 jQueryUI sortable还有一组触发某些操作的回调事件。例如,当你start或stop排序元素。
我想通过emit()
函数从这样的事件传递返回参数,所以我实际上可以看到我的回调函数中发生了什么。我还没有找到通过EventEmiiter
传递参数的方法。
我目前有以下内容。
我的指示:
@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();
}
}
这是我使用指令发出的事件的qazxsw poi:
Component
如何在我的@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);
}
}
函数中获得event
和ui
参数?
这是我到目前为止的演示:stopSort()
EventEmitter支持一个参数,该参数作为http://plnkr.co/edit/5ACcetgwWWgTsKs1kWrA?p=info传递给您的事件处理程序。
将参数传递给$event
时,将参数包装在事件对象中:
emit
然后,当您处理事件时,使用this.stopSort.emit({ event:event, ui: ui });
:
$event
stopSort($event) {
alert('event param from Component: ' +$event.event);
alert('ui param from Component: ' + $event.ui);
}
pixelbits答案在最终版本中发生了一些变化。如果您有多个参数,只需将其作为一个对象传递。
子组件:
Demo Plnkr
父组件:
this.stopSort.emit({event,ui});
@Output() stopSort= new EventEmitter<any>();
父组件中的HTML:
hereIsHeight(value) {
console.log("Height = " + value.event);
console.log("Title = " + value.ui);
}
- 此外,如果您有以下值:(前面带有“this”)
<test-child1 (stopSort)="hereIsHeight($event)"></test-child1>
它们不起作用,你需要将它们改成别的东西,然后通过如下:
this.stopSort.emit({this.event,this.ui});
*更新:阅读下面的Colin B的答案,了解使用“this”传递值的方法。
我无法添加评论,但只是想从Alpha Bravo的答案中指出你可以通过let val1 = this.event;
let val2 = this.ui;
this.stopSort.emit({val1,val2});
,你就是不能使用属性值的简写:
this.event
另请注意,如果它们作为this.stopSort.emit({ event : this.event, ui : this.ui });
通过EventEmmiter传递,那么它们将在父级中被访问为:
this.stopSort.emit({ val1, val2 });
因此,在这种情况下避免使用速记可能更为可取,以保持命名的一致性。
这样在孩子身上起作用:
hereIsHeight(value) {
console.log(`event = ${ value.val1 }`);
console.log(`ui = ${ value.val2 }`);
}
现在你只需要抓住父母的活动!