我正在尝试弄清楚如何在不保留旧引用的情况下克隆 Ext.data.Store
。
让我用一些代码更好地解释。这是源商店:
var source = Ext.create ('Ext.data.Store', {
fields: ['name', 'age'] ,
data: [
{name: 'foo', age: 20} ,
{name: 'boo', age: 30} ,
{name: 'too', age: 10} ,
{name: 'yoo', age: 80} ,
{name: 'zoo', age: 30}
]
});
下面是我想做的事的例子:
var target = source;
target.removeAll ();
// Here I need to have target empty and source unchanged
// But in this case, source is empty as well
现在,在上面的示例中,复制是通过引用完成的,而我需要通过值来完成。
所以我在文档中找到了 Ext.clone ()
但它似乎不适用于复杂的对象,比如 Ext.data.Store
:
var target = Ext.clone (source);
target.removeAll ();
// source is still empty
然后我尝试使用 Ext.data.Model.copy ()
但唯一可行的方法是:
var target = Ext.create ('Ext.data.Store', {
fields: ['name', 'age']
});
source.each (function (model) {
target.add (model.copy ());
});
现在,出于我的原因,我不想实例化另一个 Ext.data.Store
,所以我想避免这种情况:
var target = Ext.create ('Ext.data.Store', {
fields: ['name', 'age']
});
我想要这样的东西:
var target;
source.each (function (model) {
target.add (model.copy ());
});
但是,显然,它不起作用。
那么,我该如何克隆源存储?
最佳答案
ExtJS 6.x、5.x 和 4.x 解决方案
这是一个准所有 ExtJS 版本的解决方案。请注意,record.copy 已经创建了数据的克隆。无需再次 Ext.clone。
function deepCloneStore (source) {
source = Ext.isString(source) ? Ext.data.StoreManager.lookup(source) : source;
var target = Ext.create(source.$className, {
model: source.model,
});
target.add(Ext.Array.map(source.getRange(), function (record) {
return record.copy();
}));
return target;
}
关于javascript - ExtJS 4 : cloning stores,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12620424/