amp-bind JS operation inside 'on' attribute

796 Views Asked by At

I want to listen to an event (on change, in this case) and perform different actions depending on the value of a variable stored in the state. Is it possible to use the operation expr '?' expr ':' expr within the on attribute?

An example is here, where the first time the value changes (autofill equals 0) I will do an action but the rest of the times (autofills > 0) a different one. I've never seen this in practice so I do not know to which point this is possible. I tried the following two ways.

Thanks!

<select name="tamanho" id="tamanho" on="selection.autofill == 0 ?
change:AMP.setState({selection: {Tamanho: event.value,
                                 Impressao: 'Verde$ Rojo',
                                 autofill: order.autofill+1}}) :
change:AMP.setState({selection: {Tamanho: event.value}})">

<select name="tamanho" id="tamanho" on="change:AMP.setState(
selection.autofill == 0 ? {selection: {Tamanho: event.value,
                                        Impressao: 'Verde$ Rojo',
                                        autofill: order.autofill+1}} :
                          {selection: {Tamanho: event.value}})">

1

There are 1 best solutions below

2
On BEST ANSWER

As far as I know, it is not possible to write such conditions inside on attribute. The documentation states as follows:

The value for the syntax is a simple domain-specific language of the form:

eventName:targetId[.methodName[(arg1=value, arg2=value)]]

As a workaround, you can use duplicate select tags with different actions for the on attribute and conditionally render only one of them at a time by applying your condition using amp-bind. For example :

<select name="tamanho" 
        [class]="selection.autofill == 0 ? 'hide' : '' " 
        on="change:AMP.setState({ selection : 'ABCD' })">

<select name="tamanho"
        class="hide"
        [class]="selection.autofill == 0 ? '' : 'hide' " 
        on="change:AMP.setState({ selection : 'WXYZ' })">

and define class hide as follows:

.hide{
  display:none;
}

One drawback here would be that you can't assign id to the select tags since there would be duplicate ids.