Search code examples
ractivejs

Remove the first item on click in Ractive.js


I have a list of 4 items and I need to remove the first item every time the button is clicked. I implemented a simple solution based on splice method but it seems to work only on the first click. Any further click doesn't change a thing.

Here is the html:

<script type="text/ractive" id="template1">
    {{#each Posts}}
    <div style="background-color: red">{{Text}}</div>
    {{/each}}
    <button on-click="removeFirst">Remove first</button>
</script>

<main></main>

, javascript:

var ractive1 = new Ractive({
    template: '#template1',
    el: 'main',
    data: {
        Posts: [ {Text: "Post 1"}, {Text: "Post 2"}, {Text: "Post 3"}, {Text: "Post 4"} ],    
    }
});

ractive1.on({
        removeFirst: function() {
            ractive1.splice('Posts', 0, 1, []);
        }
});

and jsfiddle demo.


Solution

  • When you call splice on an array, the first argument is the index from which to start removing elements, the second argument is the number of elements to remove, and all the rest are items to insert into the array at the same location. So what you're actually doing when you call array.splice(0, 1, []) is replacing the first item with an empty array, instead of just removing it.

    Ractive's array mutation methods follow the same form, except that the first argument is the 'keypath' of the array. So if you do this...

    ractive1.splice('Posts', 0, 1);
    

    ...it works correctly.