ExtJS Store加载侦听器未被调用

Joj*_*oji 6 extjs

我有一个自定义数据存储,它存储商店是否已加载一次的信息.

/**
 * Custom DataStore which stores the information whether data has been loaded once or not.
 */
Ext.example.Store = Ext.extend(Ext.data.Store, {
    loaded: false,
    initComponent: function() {
        this.superclass().initComponent.call(this);
        this.addEvents('load','beforeload');
    },
    isLoaded : function() {
        return this.loaded;
    },
    listeners: {
        'load' :  function(store,records,options) {
            this.loaded = true;
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

这工作正常,直到最近我添加了一个'beforeload'事件监听器到这个商店的实例.现在不会调用'load'侦听器.

var accountsDataStore = new Ext.example.Store({

    id : 'account',
    proxy : new Ext.data.HttpProxy({
        url : 'app/account/fetch/all',
        method : 'post',
        api : {
            destroy : 'app/account/delete'
        }
    }),
    reader : accountReader,
    writer : accountWriter,
    remoteSort : true,
    sortInfo : {
        field : 'createdOn',
        direction : "DESC"
    },
    listeners: {
        beforeload: function(store, options) {
            var sort = options.params.sort;
            // setting the sort parameters to match the property names in the DTO
            switch(sort) {
                case 'company' :
                    options.params.sort = 'company.name';
                    break;
                default:
                    // do nothing
            }
        }
    }

});
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?另外,请告诉我你的改进建议

Jua*_*des 5

问题是你永远不应该在原型上设置对象,除非你真的知道它意味着什么(它将由所有实例共享,并且可以在每个实例的基础上被覆盖)

在Ext JS中,我只在原型上设置配置选项,这只是为了方便,可以被调用者覆盖.

你的第一堂课Ext.example.Store将听众放在原型上.然后通过将侦听器对象传入配置,然后在accountsDataStore中覆盖它.

要解决您的问题,不要在原型上设置监听器,只需this.on('event')从构造函数调用即可.

/**
 * Custom DataStore which stores the information whether data has been loaded once or not.
 */

Ext.example.Store = Ext.extend(Ext.data.Store, {
    loaded: false,
    constructor: function() {
        this.superclass().constructor.call(this);
        // No need to call this, you're not adding any events
        // this.addEvents('load','beforeload');
        this.on('load', function(store,records,options) {
            this.loaded = true;
        }, this);
    },
    isLoaded : function() {
        return this.loaded;
    }
});
Run Code Online (Sandbox Code Playgroud)


Swa*_*war 0

好吧,我认为范围有问题。请尝试这样操作:

listeners: {
        'load' :  {
            fn : function(store,records,options) {
                 console.log(this, this.loaded);
                 this.loaded = true;
            },
            scope : this
        }
    }
Run Code Online (Sandbox Code Playgroud)

或者您可以使用:

listeners: {
        'load' :  function(store,records,options) {
            store.loaded = true;
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 事实上,负载监听器甚至没有被调用。 (2认同)