You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ExtJS 6.2.1 如何在工具类中正确配置并使用store?

ExtJS 6.2.1 自定义单例工具类使用Store的解决方案

根因说明

Ext.grid.Grid 等官方组件继承自 Ext.Component,框架内置了 store 配置的自动解析逻辑,当配置为字符串时会自动通过 Ext.data.StoreManager 查找匹配的 store 实例。自定义的普通单例类没有内置该解析逻辑,所以配置的 store 会保留原始字符串值,不会自动转成实例。

三种实现方案

方案1:构造函数初始化时一次性解析

适合store不会动态更换的场景,在单例构造阶段完成转换:

Ext.define('App.MyClass', {
    singleton : true,
    store     : 'myStore',

    constructor: function(config) {
        this.callParent([config]);
        // 兼容字符串、配置对象、实例三种入参
        if (this.store && !this.store.isStore) {
            this.store = Ext.data.StoreManager.lookup(this.store);
        }
        return this;
    }
});

方案2:配置处理器自动解析(推荐)

符合Ext类系统的规范,后续动态修改store配置也会自动完成解析:

Ext.define('App.MyClass', {
    singleton : true,

    config: {
        store: 'myStore'
    },

    // store配置的处理钩子,赋值时自动触发
    applyStore: function(store) {
        if (!store || store.isStore) {
            return store;
        }
        return Ext.data.StoreManager.lookup(store);
    }
});

使用时直接调用生成的get/set方法即可:

// 获取store实例
const store = App.MyClass.getStore();
// 动态更换store,传入字符串也会自动解析
App.MyClass.setStore('otherStore');

方案3:使用时实时查找

适合store可能动态销毁、重建的场景,避免持有过时的实例:

Ext.define('App.MyClass', {
    singleton : true,
    storeId: 'myStore',

    doSomething: function() {
        const store = Ext.data.StoreManager.lookup(this.storeId);
        if (!store) {
            return;
        }
        // 后续业务逻辑
    }
});

注意点

  • 确保需要引用的store已经通过id或者alias: 'store.xxx'完成配置,StoreManager才能正确识别
  • 如果store是懒加载的,不要在单例初始化阶段解析,建议选择方案3实时获取

内容的提问来源于stack exchange,提问作者user5507535

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:24:00