3

In an event handler I need to determine the DOM Element which got clicked. I would expect to use jqEvent.target.attributes['tag'] where jqEvent is of type JQueryEventObject. But 'target' is defined in lib.d.ts as of type EventTarget which contains nothing I can use...

Have I missed something?

1
  • 2
    lib.d.ts like any declaration file isn't the final word on what's going to happen. If jqEvent really is of type JQueryEventObject you can always cast it. Commented Jul 16, 2013 at 20:29

3 Answers 3

5

I use this and it works fine...

    private funct(event: JQueryEventObject) {
        var state = $(event.target).prop('checked');
    }
Sign up to request clarification or add additional context in comments.

3 Comments

More info on the $event parameter: docs.angularjs.org/guide/expression#-event-
@rinogo We are talking about JQuery, not Angular... :D
Thanks for clarifying, @Matěj Pokorný! FWIW, Angular still uses "jqLite" (or full jQuery if its loaded), so this is still relevant. Your answer helped me with my Angular-based Typescript, so thanks! :) I'll leave my link in case it helps any of the Angular peeps who hit this question.
1

Here is the definition of EventTarget (found in dom.generated.d.ts, distributed with TypeScript):

interface EventTarget {
    removeEventListener(type: string, listener: EventListener, useCapture?: boolean): void;
    addEventListener(type: string, listener: EventListener, useCapture?: boolean): void;
    dispatchEvent(evt: Event): boolean;
}

There could be other classes that implement EventTarget in order to attach events, so the safest API definition is to set Event.target to the object that implements EventTarget where the listeners are attached.

In the jQuery context, Event.target will almost certainly be of type HTMLElement (not type JQuery as in Andree's answer). For your example of jqEvent.target.attributes['tag'], the correct way is to notify the compiler that it is actually a Node (grandparent interface of HTMLElement), which does have the attributes property:

(<Node> jqEvent.target).attributes['tag']

The above cast could also be to HTMLElement if you are explicitly accessing properties of the more specific interface. Using the most general interface possible is considered object-oriented best practice.

Comments

-1

I think it is actually a mistake in the declaration. It's supposed to be of type JQuery. But is can be casted either by Typescript construct

<JQuery>(event.target)[0].attributes['id'];

or as a parameter to the constructor to JQuery

$(event.target)[0].attributes['id'];

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.