简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM