ractivejs / ractive

Next-generation DOM manipulation
http://ractive.js.org
MIT License
5.94k stars 396 forks source link

How to... #3231

Closed dagnelies closed 6 years ago

dagnelies commented 6 years ago

To put it bluntly, I'd like to make something like this:

{{#each items}}
  <li class-active="isLinked(@keypath, 'selected')" on-click="@this.link(@keypath, 'selected')">... </li>
{{/each}}

{{#with selected}}
    ...
{{/with}}

How would you advise to do this?

It's for the example here: https://dagnelies.github.io/ractive-examples/editor4panes.html?url=content/linked_item.html

fskreuz commented 6 years ago

I'd do it like this.

    <div class="col-sm-4">
        <ul class="list-group">
        {{#each people}}
            <li class="list-group-item" class-active="selected === @index" on-click="@this.set('selected', @index)">{{firstname}} {{lastname}}</li>
        {{/each}}
        </ul>
    </div>
    <div class="col-sm-4">
        {{#if selected !== null}}
            <label>First name</label>
            <input class="form-control" value="{{people[selected].firstname}}" />
            <label>Last name</label>
            <input class="form-control" value="{{people[selected].lastname}}" />
        {{/if}}
    </div>
    <div class="col-sm-4">
        The data:
        <pre>{{JSON.stringify(this, null, 2)}}</pre>
    </div>
var ractive = new Ractive({
    target: '#target',
    template: '#template',
    data: {
        selected: null,
        people: [{
            firstname: "Alice",
            lastname: "Wonderlands"
        },{
            firstname: "Bob",
            lastname: "Marley"
        },{
            firstname: "Charlie",
            lastname: "Angel"
        }]
    }
});
giovannipiller commented 6 years ago

On a hurry and from mobile, so I might be missing something but, how about this?

{{#each items as item}}
  <li class-active="item === selected" on-click="@this.link(@keypath, 'selected')">... </li>
{{/each}}
evs-chris commented 6 years ago

Was about to post exactly what @giovannipiller said. If object identity won't work for you because you're not dealing with objects or you have the same object multiple times in the list, you could use readLink, but if identity works, that's by far the easiest route.

dagnelies commented 6 years ago

@fskreuz : although this possibility works for the provided example, it becomes problematic once you use structures like nested lists or trees.

@giovannipiller @evs-chris : that's exactly what I did first. I still find it the most intuitive. Sadly, equality don't seem to work on linked objects.

evs-chris commented 6 years ago

It should work, and does in a simple example. Is there something more involved?

dagnelies commented 6 years ago

Thanks. {{. === ~/selected}} works indeed. What I tried was {{. === selected}} which doesn't.

I guess I ended up again in the same trap as #3193