How To Make An Object Property Function Into An Eventemitter?
Solution 1:
By passing parent functions to the child, you are tightly coupling the parent component to the child (which is normally not recommended). In other words, you are revealing information about parent methods to the child. Ideally, the child should not know anything about the parent. (This makes the (child) component more reusable.)
Instead of your current approach, i.e., instead of passing down parent function references to the child, pass down some IDs or some other unique values. When a click event occurs in the child, pass the ID or unique value back up to the parent (using an output property/EventEmitter):
<li *ngFor="#option of options" (click)="myEmitter.emit(option.uniqueValue)"></li>
Then in the parent, map that value to the appropriate function call and call it:
<child [options]="options" (myEmitter)="doWork($event)"></child>
doWork(uniqueValue) {
// map uniqueValue to some function and call it
}
Another added benefit with this approach is that you won't have to mess with this
contexts.
Solution 2:
this keyword in JavaScript depends on context. In most cases, the value of this is determined by how a function is called. Since TypeScript is a typed superset of JavaScript it behaves the same, please follow the links below.
ECMAScript 5 introduced Function.prototype.bind. Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.
function's this keyword, bind method
You could also use arrow functions as alternative.
Post a Comment for "How To Make An Object Property Function Into An Eventemitter?"