Search code examples
ractivejs

With clause changes keypath


I have the following template:

{{#each Posts}}
{{#with { Post: this } }}
  <h2 on-click="doSomething">{{Title}}</h2>
  ...
{{/with}}
{{/each}}

When I click on the header and doSomething get called, I get "${{Post:Posts-0}}" in event keypath. But I need to get access to the post keypath: "Posts.0" to modify some of its properties. What is the right way to achieve that?


Solution

  • Using a {{#with { a: b } }} block for aliasing in Ractive has some limitations, as it's not true aliasing, it's simply creating an expression with an object literal. It's a needed enhancement to offer true aliasing with something like {{#each Post in Posts}} or {{#each Posts as Post}}.

    As far as what you can do today, you can add the keypath to the with block:

    {{#with { Post: this, keypath: @keypath } }}
    

    And then either pass in:

      <h2 on-click="doSomething:{{keypath}}">{{Title}}</h2> 
    

    Or access in the event via this.event.context.keypath. See http://jsfiddle.net/w0npbnrz/ for both of these in action.

    You also could use {{#each Posts:p}} in which case you could get the keypath via 'Posts.' + this.event.index.p.