How to bind variable window['array[element]'] in Ractive.js?

86 Views Asked by At

There is a need to have a two-way binding for a variable with such untypical name like "array[element]".

The syntax below works but when I change 0 to @index it gets broken. Adding back slashes before brackets [ ] does not work as well.

<input type="text" name="prices[{{@index}}]" value="{{someForm.inputs["prices[0]"].value}}" />

What is the proper syntax to get the variable binded?

2

There are 2 best solutions below

2
Amadan On

You can use @context:

Ractive.DEBUG = false;
var ractive = Ractive({
  target: output,
  template: `
    {{ @context.get('array[element]') }}
  `,
  data: { 'array[element]': "FOO" }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/ractive/1.0.0-build-99/ractive.min.js"></script>
<div id="output"></div>

0
ZenitoGR On

there is a syntax to use inside html tag attributes:

value=`someForm.inputs["prices[${@index}]"].value`
  1. use backticks to surround the value text
  2. use ${} syntax to input a variable

source: One of the nice things about expression context is that, combined with Ractive's unquoted attribute value support, you can avoid quote plileup for string expressions using backticks. Some text editors don't really like backticks on attributes, though. https://ractive.js.org/api/#directives