jeff jeff - 3 years ago 129
TypeScript Question

typescript, making a c# like delegate, fat arrows, and this

I'm working in an Angular/Typescript project. I have the following construct i'm building as a light weight pubsub. This is the subscription in a fluent syntax.

.HandleEventWithThisMethod( (PubSubEventArgs) =>
{self.handlePEvent(PubSubEventArgs); } )
.ApplyFilterPredicate((res: PubSubEventArgs) => {
return (res.sourceObjectId === self.objectId);

The part i'd like to simplify is the HandleEventWithThis method. In C#, it'd be

When I do away with the fat-arrow stuff, I lose track of THIS in the handlePEvent.

Can someone tell me how to simplify the syntax of the

Answer Source

You have some extra brackets and such that you don't need. You can simplify like this:

    .Create(PubSubTopic.testEvent, this.objectId)
    .HandleEventWithThisMethod(args => self.handlePEvent(args))
    .ApplyFilterPredicate(res => res.sourceObjectId === self.objectId);


    .Create(PubSubTopic.testEvent, this.objectId)
    .ApplyFilterPredicate(res => res.sourceObjectId === self.objectId);

You can't pass self.handlePEvent directly is that a function is not inherently tied to the object. If you pass the function reference around and then call the function, by default this will not be the object but will be the Window.

You can force the function to be bound to the object with a call to bind as in self.handlePEvent.bind(self).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download