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.

SubscribeEvent.Create(PubSubTopic.testEvent,
this.objectId)
.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
HandleEventWithThisMethod(handlePEvent)


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
.HandleEventWithThisMethod
?

Answer Source

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

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

or

SubscribeEvent
    .Create(PubSubTopic.testEvent, this.objectId)
    .HandleEventWithThisMethod(self.handlePEvent.bind(self))
    .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