Search code examples
javascriptractivejs

Update value in collection


I have a collection of posts as data:

var ractive = new Ractive({
    el: '#templateContainer',
    template: '#template',
    data: {
        Posts: [{"Id":"posts/97", Content="Blog post test", Date="Something"}, ...];
    }
});

At some point I receive a notification that the blog post content has changed:

funcion onBlogPostContentChanged(postId, newContent) {
    ractive.set(..., newContent);
}

The problem is that I don't know how to specify ractive.set so that the content is changed for a blog post with a specific Id.


Solution

  • You can set the keypath via the array index and the property:

    function onItemChanged(id, newContet) {
        var posts = r.get('Posts'), index = -1
    
        for(var i = 0; i < posts.length; i++){
            if(post[i].Id === id){
                index = i
                break
            }        
        }
    
        if(index !== -1){
            r.set('Posts.' + index + '.Content', newContent)
        }
    
        // or if using "magic: true"**
        Posts[index].Content = newContent
    }
    

    See http://jsfiddle.net/pj6myzch/ for working example.

    ** http://docs.ractivejs.org/latest/magic-mode