javascript - 更新集合中的值

标签 javascript ractivejs

我有一组帖子作为数据:

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

有时我收到一条通知,表明博客文章内容已更改:

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

问题是我不知道如何指定 ractive.set 以便更改具有特定 ID 的博客文章的内容。

最佳答案

您可以通过数组索引和属性设置键路径:

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
}

参见http://jsfiddle.net/pj6myzch/用于工作示例。

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

关于javascript - 更新集合中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26694939/

相关文章:

javascript - Ractive with Require 例子

javascript - 当我追加到数组时,Ractive.js 会追加还是重建所有内容?

javascript - 如何修复 ractive.js 中的 "Could not find template for partial"?

javascript - ractive.js 多个复选框

javascript - Extjs使用formBind : true,不禁用提交按钮

javascript - 这个 JS 有什么问题?

Javascript 条件顺序评估

javascript - 组合和扩展 Ractive 组件

javascript - 地理定位 api 中是否有类似 isGeolocationAllowed 或 isGeolocationAllowedForever 的函数?

javascript - 当我在字段中输入数字时,如何实时显示结果?