通过 "id" 而不是对象索引获取 Ractive 数据
Getting Ractive data by, say, "id", rather than by the object index
假设我的 Ractive 数据是这样的:
items: [
{ id: 16, name: "thingy" },
{ id: 23, name: "other thingy"}
]
我知道我可以这样做以获得第一个项目:
ractive.get('items.0')
但是我如何获取(或删除或更新)id 为 23 的项目?
主要是 javascript 问题,但您可以将方法放在您的 ractive 实例或原型上。假设你的数组不是太大并且使用 find and findIndex,你可以这样做:
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
}
}
如果你想使用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;
};
假设我的 Ractive 数据是这样的:
items: [
{ id: 16, name: "thingy" },
{ id: 23, name: "other thingy"}
]
我知道我可以这样做以获得第一个项目:
ractive.get('items.0')
但是我如何获取(或删除或更新)id 为 23 的项目?
主要是 javascript 问题,但您可以将方法放在您的 ractive 实例或原型上。假设你的数组不是太大并且使用 find and findIndex,你可以这样做:
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
}
}
如果你想使用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;
};