Search code examples
javascriptdom-eventsractivejs

RactiveJS Should Target The Element Triggering Proxy Event, Not It's Children


I'm trying to add an active classname to the li that is clicked on. Showing that it's selected.

My template:

 var legCatagoryTemplate = "<ul>{{#legs:i}}<li><a href='#' on-click='selectCategory:{{this}},{{i}}' data-id='{{i}}'><figure><div class='imgWrapper'><img src='{{preview}}'></div><figcaption><h4>{{name}}</h4><p>W: {{width}}&quot;  H:<span></span>: {{material}}</p></figcaption></figure></a></li>{{/legs}}</ul>";
        

How its called:

var legCategoryView = new Ractive({
        el: "#catalog",
        template: legCatagoryTemplate,
        data: response_from_ajax
    });

How I'm handling the event:

legCategoryView.on('selectCategory', function ( event, self, index ){
    console.log(event.target, self, index);
}

What I've found:

event.target is the element inside of the a that was clicked (eg div.imgwrapper, figcaption)

Non Ractive behaves similarly: click event on a div should not be triggered by it's children

What is a good solution to targeting the element with the on-click proxy object?


Solution

  • You might just traverse the DOM and find the li element but that can cause troubles in certain situations. If you call ractive.set('legs', new_data), Ractive will reuse the existing nodes, so your class will remain there. There are several solutions for this problem (the third is probably the best):

    1. Use ractive.merge() instead of ractive.set().
    2. Use splice() and push() instead of ractive.set().
    3. Change your template and let Ractive manage the class:
    <ul>
    {{#legs:i}}
        <li class="{{#.active }}active{{/}}">
            <a href='#' on-click='selectCategory:{{this}},{{i}}' data-id='{{i}}'>
                <figure>
                    <div class='imgWrapper'><img src='{{preview}}'></div>
                    <figcaption>
                        <h4>{{name}}</h4>
    
                        <p>W: {{width}}&quot; H:<span></span>: {{material}}</p>
                    </figcaption>
                </figure>
            </a>
         </li>
    {{/legs}}
    </ul>
    
    ractive.on('selectCategory', function ( e ) {
        ractive.set(e.keypath + '.active', true);
    });