Wil*_*ilk 14 javascript model extjs store extjs4
我试图弄清楚如何在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}
]
});
Run Code Online (Sandbox Code Playgroud)
按照我想要做的一个例子:
var target = source;
target.removeAll ();
// Here I need to have target empty and source unchanged
// But in this case, source is empty as well
Run Code Online (Sandbox Code Playgroud)
现在,在上面的例子中,副本是通过引用完成的,而我需要按值来完成.所以我Ext.clone ()
在文档中发现它似乎不适用于复杂的对象,例如Ext.data.Store
:
var target = Ext.clone (source);
target.removeAll ();
// source is still empty
Run Code Online (Sandbox Code Playgroud)
然后我尝试了,Ext.data.Model.copy ()
但唯一的方法是这样做:
var target = Ext.create ('Ext.data.Store', {
fields: ['name', 'age']
});
source.each (function (model) {
target.add (model.copy ());
});
Run Code Online (Sandbox Code Playgroud)
现在,由于我的原因,我不想实例化另一个Ext.data.Store
,所以我想避免这个:
var target = Ext.create ('Ext.data.Store', {
fields: ['name', 'age']
});
Run Code Online (Sandbox Code Playgroud)
我想要这样的东西:
var target;
source.each (function (model) {
target.add (model.copy ());
});
Run Code Online (Sandbox Code Playgroud)
但是,显然,它不起作用.
那么,我该如何克隆源存储?
Chr*_*eek 13
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;
}
Run Code Online (Sandbox Code Playgroud)
kna*_*lli 12
ExtJS 3.x解决方案
试试这个:
cloneStore : function(originStore, newStore) {
if (!newStore) {
newStore = Ext.create('Ext.data.Store', {
model : originStore.model
});
} else {
newStore.removeAll(true);
}
var records = [], originRecords = originStore.getRange(), i, newRecordData;
for (i = 0; i < originRecords.length; i++) {
newRecordData = Ext.ux.clone(originRecords[i].copy().data);
newStore.add(new newStore.model(newRecordData, newRecordData.id));
}
newStore.fireEvent('load', newStore);
return newStore;
}
Run Code Online (Sandbox Code Playgroud)
注意:Ext.ux.clone
是一个分离的插件(你会发现它),它可以深度克隆一个对象.也许,Ext JS 4提供了一个熟悉的东西,我不知道..我从Ext JS 3.x开始使用这个特殊的克隆
memory
在创建新商店时可能需要指定代理(我现在不确定,因为我总是使用"提供"方式.
ExtJS 4.x解决方案
function deepCloneStore (source) {
var target = Ext.create ('Ext.data.Store', {
model: source.model
});
Ext.each (source.getRange (), function (record) {
var newRecordData = Ext.clone (record.copy().data);
var model = new source.model (newRecordData, newRecordData.id);
target.add (model);
});
return target;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21761 次 |
最近记录: |