在控制器中设置商店事件的侦听器

Dem*_*nis 28 javascript model-view-controller extjs extjs4

我有一个带有商店,模型和一些视图的控制器.

我需要在控制器中监听存储beforesyncwrite事件,但我不知道如何在controllers control-function中设置这些监听器.

我的商店看起来像这样:

Ext.define('DT.store.UsersStore', {
    extend : 'Ext.data.Store',
    model : 'DT.model.User',
    id : 'myStore'
    autoSync : true,
    proxy : {
        type : 'ajax',
        api : {
            read : '/load_entries',
            update : '/update_entry'
        },
        reader : {
            type : 'json',
            root : 'user',
            successProperty : 'success'
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

现在我尝试听我的控制器中的事件:

...
init : function () {
    this.control({
        'myStore' : {
            beforesync : this.doSomething,
            write : this.doSomethingElse
        }
    });
},
...
Run Code Online (Sandbox Code Playgroud)

我的预期结果是,在触发事件时将执行函数.但此时他们被解雇时没有任何反应.

我怎样才能让它发挥作用?

Mol*_*Man 33

你的方式是可能的,但它并不理想,IMO.更好的方法是使用控制器的商店getter.在你的情况下,代码将是这样的:

init : function () {
    // every controller has getters for its stores.
    // For store UsersStore getter would be getUsersStoreStore()
    this.getUsersStoreStore().addListener('write',this.finishedLoading, this);
    this.control({
        // widgets event handlers
    });
},
Run Code Online (Sandbox Code Playgroud)

  • 甚至比我的解决方案更好.谢啦.这个社区很棒. (2认同)

Jam*_*hon 19

这是Molecular Man答案的另一种语法.

而不是写作,

init : function () {
    this.getUsersStoreStore().addListener('write',this.finishedLoading, this);
    this.control({
        // widgets event handlers
    });
},
Run Code Online (Sandbox Code Playgroud)

你可以写

init : function () {
    this.getUsersStoreStore().on({
        write: this.finishedLoading,
        scope: this
    });
    this.control({
        // widgets event handlers
    });
},
Run Code Online (Sandbox Code Playgroud)

我认为这个替代定义会更好一些.

我从Izhaki给我的回答中得到了这个.

  • 在这个页面上的所有解决方案中只有`this.getUsersStoreStore().on({..`为我工作.(使用4.2.1) (2认同)

小智 5

对于Extjs 4.2.1,如果您使用'storeId'而不是id和'listen'函数而不是'control',那么访问商店监听器的初始方式实际上是可行的:

Ext.define('DT.store.UsersStore', {
    extend : 'Ext.data.Store',
    model : 'DT.model.User',
    storeId : 'myStore'
    ....

init : function () {
    this.listen({
        store: {
           '#myStore' : {
               beforesync : this.doSomething,
               ...
Run Code Online (Sandbox Code Playgroud)