计算/转换前端中的 id 字段



我正在尝试计算/转换前端的id,但ExtJS没有完成。例:

fields: [{
name: 'test',
type: 'int'
}, {
name: 'id',
depends: [
'test'
],
convert: function(v, rec) {
return rec.get('test')%10;
}
}]

如果我现在将"test"的值为 1、2、3、5、11 的五条记录加载到存储中,

  • id 应该是根据 "test" 的值计算得出的 int,而不是自动生成的。
  • Test=11 的记录应具有 id=1,
  • 因此覆盖 test=1 的记录(也是 id=1)

https://fiddle.sencha.com/#view/editor&fiddle/2gpp

但是,这不会按预期工作,ID 始终是自动生成的,因此,重复数据删除无法按预期工作。

为什么会这样,我该如何解决?

您应该考虑使用映射方法接收您使用 reader 配置的原始 json 数据,并且可以执行任何类型的预处理。 而计算和转换方法对需要在使用前在字段中定义的数据的访问受到限制。

fields: [{
name: 'test',
type: 'int'
}, {
name: 'id',
mapping(data){
return data.test % 10;   
}
}]

不工作的主要原因是idProperty模型。

Defaults to:'id'

如果您将模型或字段名称中的idProperty更改为任何其他而不是id,则depends配置将起作用。

您可以使用depends配置检查此工作FIDDLE。希望这将有助于/指导您解决depends配置的问题。

代码片段

Ext.application({
name : 'Fiddle',
launch : function() {
Ext.define('ModelName', {
extend: 'Ext.data.Model',
idProperty:'test',
fields: [{
name: 'test',
type: 'int'
}, {
name: 'id',
depends: ['test'],
convert: function(v, rec) {
return rec.get('test')%10;
}
}]
});
var store = Ext.create('Ext.data.Store', {
model: 'ModelName',
proxy: {
type: 'ajax',
url: 'data1.json',
reader: {
type: 'json',
rootProperty: 'data'
}
}
});
store.on('load', function() {
// Due to clashes between the calculated id,
// the store should contain four records.
console.log(store.getRange());
});
store.load();
Ext.define('ModelName1', {
extend: 'Ext.data.Model',
fields: [{
name: 'test',
type: 'int'
}, {
name: '_id',
depends: ['test'],
convert: function(v, rec) {
return rec.get('test')%10;
}
}]
});
var store1 = Ext.create('Ext.data.Store', {
model: 'ModelName1',
proxy: {
type: 'ajax',
url: 'data1.json',
reader: {
type: 'json',
rootProperty: 'data'
}
}
});
store1.on('load', function() {
// Due to clashes between the calculated id,
// the store should contain four records.
console.log(store1.getRange());
});
store1.load();
}
});