通过“id”获取Ractive数据,而不是通过对象索引获取

时间:2015-04-01 05:08:18

标签: ractivejs

说我的Ractive数据如下所示:

items: [
  { id: 16, name: "thingy" },
  { id: 23, name: "other thingy"}
]

我知道我可以这样做以获得第一项:

ractive.get('items.0')

但是如何获取(或删除或更新)id为23的项目?

2 个答案:

答案 0 :(得分:1)

主要是一个javascript问题,但您可以将方法放在ractive实例或原型上。假设您的数组不是太大且使用findfindIndex,您可以执行以下操作:

Ractive.prototype.getIndexById = function(keypath, id){
    this.get(keypath).findIndex(function(each){
        return each.id === id;
    });
}

Ractive.prototype.getById = function(keypath, id){
    return this.get(keypath).find(function(each){
        return each.id === id;
    });
}

Ractive.prototype.delete = function(keypath, id){
    return this.splice(keypath, this.getIndexById(id), 1);
}

Ractive.prototype.update = function(keypath, id, data){
    return this.set(keypath + '.' + this.getIndexById(id), data);
}

但如果您只是试图处理发生某项操作的项目,则应使用上下文:

{{#items:i}}
<li on-click='selected'>{{name}}</li>
<!-- or -->
<li on-click='selected(this, i)'>{{name}}</li>
{{/items}}

代码

new Ractive({
    ...
    selected: function(item, index){
        // in lieu of passing in, you can access via this.event:
        var item = this.event.context // current array member
        var index = this.event.index.i // current index
    },
    oninit: function(){
        this.on('selected', function(){
            // same as method above
        }
    }

答案 1 :(得分:0)

如果你想使用jQuery,可以这样做:

Ractive.prototype.getKeyById = function(keypath, id) {
  var key;
  key = -1;
  $.each(this.get(keypath), function(i, data) {
    if (data.id === id) {
      key = i;
      return false;
    }
  });
  return key;
};