Attach ExtJS MVC controllers to DOM elements, not components

前端 未结 5 1432
执念已碎
执念已碎 2020-12-13 05:10

Is there a way to use the Ext.app.Controller control() method, but pass in a DOM query? I have a page that contains standard links and would like to add a click handler to

5条回答
  •  既然无缘
    2020-12-13 05:44

    I have found a work around for this problem. It isn't as direct as one may hope, but it leaves all of your "action" code in the controller.

    requirment: Wrap the html section of your page in an actual Ext.Component. This will likely be the case either way. So for instance, you may have a simple view that contains your HTML as follows:

    Ext.define('app.view.myView', {
        extend: 'Ext.panel.Panel',
        alias: 'widget.myView',
        title: 'My Cool Panel',
        html: '
    ', initComponent: function(){ var me = this; me.callParent(arguments); } });

    Then in the controller you use the afterrender event to apply listeners to your DOM elements. In the example below I illustrate both links (a element) and input elements:

    Ext.define('app.controller.myController', {
    extend: 'Ext.app.Controller',
    
        init: function() {
            this.control({
                'myView': {
                   afterrender: function(cmp){
                        var me = this; //the controller
                        var inputs = cmp.getEl().select('input'); // will grab all DOM inputs
                        inputs.on('keyup', function(evt, el, o){
                            me.testFunction(el); //you can call a function here
                        });
    
                        var links = cmp.getEl().select('a'); //will grab all DOM a elements (links)
                        links.on('click', function(evt, el, o){ 
                            //or you can write your code inline here
                            Ext.Msg.show({
                                title: 'OMG!',
                                msg: 'The controller handled the "a" element! OMG!'
                            });
                        });
                    }
                }   
            });
        },
        testFunction: function(el) {
            var str = 'You typed ' + el.value;
            Ext.Msg.show({
                title: 'WOW!',
                msg: str
            });
        }   
    });
    

    And there you have it, DOM elements handled within the controller and adhering to the MVC architecture!

提交回复
热议问题