0

版本 ExtJs - 6.2.1 考虑到下面指定的示例代码,我很想知道是否有更好的方法来实现我可以处理一些检查的地方。

Ext.define('MainApp.view.main.MainController', {
    extend: 'Ext.app.ViewController',
    ...    
    listen: {
        controller: {
            // listen to some components events
            'componentController':{
                'event1': 'onEvent1',
                'event2': 'onEvent2'
            }
        }
    },

    onEvent1: function(){

        // can i avoid this and do something better ??
        this.commonEventHandlingChecks();

        // event 1 handling logic
    },

    onEvent2: function(){

        // can i avoid this and do something better ??
        this.commonEventHandlingChecks();

        // event 2 handling logic
    },

    commonEventHandlingChecks: function(){
       // some logic to do some custom validations      
    }

});

不是在我的控制器中的每个侦听器上调用方法“commonEventHandlingChecks”,有没有更好的方法来执行所有常见的事件处理检查。可能通过覆盖控制器或 Ext.util.Event 中的某些方法

4

1 回答 1

1

Ext.Mixin确实有一个mixinConfig beforeAPI 可以在 mixin 上添加一个函数并执行它。如果返回false,则不会执行之前放置的函数。这记录在此处的类描述中(链接到 6.2.1 版本,因为您说您正在使用它)

除了 mixin 必须知道它被混合到的类上需要保护哪些方法之外,这将起作用。如果您想在不同的类中使用 mixin,这不会很好地扩展。为此,我会做一些更高级的事情,但要保持与beforeAPI 提供给您的功能相同的功能。这个 mixin 看起来像:

Ext.define('MyAuthMixin', {
    extend: 'Ext.Mixin',

    onClassMixedIn: function (targetClass) {
        const proto = targetClass.prototype
        const config = proto.config
        const protectedMethods = config.protectedMethods || proto.protectedMethods
        // change this method name if you want something else
        const checkAuth = this.prototype.checkAuth

        if (protectedMethods) {
            Ext.Object.each(protectedMethods, function (key, value) {
                if (value && proto[ key ]) {
                    targetClass.addMember(key, function () {

                        // execute the checkAuth methods
                        // change this variable to change the method name
                        if (checkAuth.apply(this, arguments) !== false) {
                            return this.callParent(arguments);
                        }
                    });
                }
            });
        }
    },

    checkAuth: function () {
        // return false to stop calling
        return !!MyApp.$user
    }
})

不要被那个onClassMixedIn功能吓到。基本上,它将方法放在checkAuth被告知要保护的方法之前,如果您返回falsecheckAuth那么它将不会执行该受保护的方法。

有关如何使用它并查看它的示例,我创建了这个fiddle。类中的实现将是这一部分:

mixins: [
    'MyAuthMixin'
],

config: {
    // put in a config object so subclass and superclass merging
    // which is also why it's an object as a subclass can disable
    // a protected method
    protectedMethods: {
        'onEvent1': true,
        'onEvent2': true
    }
},

要不保护方法,您可以将其排除在外或将其设置为false. 设置为的原因false只是一个子类可以禁用检查,如果它扩展了一个打开它的类。这个 mixin 将适用于任何类,而不仅仅是控制器。它可以是组件或单例或存储,任何。

于 2018-06-21T13:10:12.557 回答