Inline Events

Another feature Metal.js has that can be very useful is the ability to declare events inside templates, directly on the desired element. Besides being simple and intuitive, this feature allows Metal.js to handle attaching events itself, and so this can be done in the best way possible, with delegates for example, without the user having worry about that at all. These events are also automatically detached when the component is disposed.

Inline listeners - via function name

You can add DOM event listeners easily through your templates, like this:

The above code declares that whenever the x button is clicked, the close function from the component should be called.

Inline listeners - via function reference

If you prefer though, you can also pass the actual function reference (instead of just its name) as an inline listener.

That will work exactly the same way as the previous example.

Inline listeners - nested components

When using nested components it's also possible to inline events by using the events property:

This will cause the close function from the sub component to be called whenever a click event triggers for the elements that match the given selector.

In case you want to listen to the event with a function from the parent component, just pass the function reference instead of a string, like this:

Besides dom events, you can also listen to custom events from the sub component in this same way:

Inline listeners - alternative usage

Besides the on[EventName] format you can also use data-on[eventname] for adding inline listeners. For example:

Note that this format is supported mainly to enable doing progressive enhancement, when running soy templates via Java for example. When templates using the on[EventName] format run in Java they will output elements with these as actual attributes, which can cause errors in the browser. In JavaScript these are used as element properties instead, so this problem doesn't occur.

So feel free to use the format you like best, or that better fits your needs.