Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExtJS 4.1 Call One Controller From Another

Note: I'm a total ignoramus regarding javascript.

I've broken my ExtJS 4.1 MVC app out into several controllers like:

/app/controller/Auth
    |          |Quiz
    |          |Result
    |          |Blah...
    |model/...

I want to respond to an "event", not a DOM Event, rather a Ext.form.action.Submit.success event by calling functions in both my Auth and Quiz controllers. The summarized code for the first part is here:

// File: app/controller/Auth.js
attemptLogin : function() {
    var form = Ext.ComponentQuery.query('#loginpanel')[0].form;
    if (form.isValid()) {
        form.submit({
        success : function(form, action) {
            // THIS IS THE FUNCTION FROM THE CURRENT CONTROLLER
            Assessor.controller.Auth.prototype.finishLogin();
            // THIS IS THE FUNCTION FROM THE OTHER CONTROLLER
            Assessor.controller.Quiz.prototype.setupAssessment();
        },

This works but feels wrong. Is there a proper way to do this? It seems like I should fire a unique event that is listened to by both controllers, but I can't understand how to do that with Ext.Event. Any guidance?

Thanks! I'm really grateful for all the great ideas and advice.

like image 919
justinzane Avatar asked Aug 22 '12 03:08

justinzane


1 Answers

It makes sense to me to fire a custom event from the form and simply listen to it in both your controllers, like what you said here:

It seems like I should fire a unique event that is listened to by both controllers

// File: app/controller/Auth.js
attemptLogin : function() {
    var form = Ext.ComponentQuery.down('#loginpanel').form;
    if (form.isValid()) {
        form.submit({
        success : function(form, action) {
            // fire the event from the form panel
            form.owner.fireEvent('loginsuccess', form.owner);
        },

Then in each of your controllers you can listen to it with Controller#control, like this:

Ext.define('YourApp.controller.Auth', {
    extend: 'Ext.app.Controller',

    init: function() {
        var me = this; 

        me.control({

            '#loginpanel': {

                loginsuccess: me.someHandler

            }
        });
    },

    someHandler: function(form) {
        //whatever needs to be done
        console.log(form);
    }
}

And then add the same thing to your Quiz controller:

Ext.define('YourApp.controller.Quiz', {
    extend: 'Ext.app.Controller',

    init: function() {
        var me = this; 

        me.control({

            '#loginpanel': {

                loginsuccess: me.someOtherHandler

            }
        });
    },

    someOtherHandler: function(form) {
        //whatever needs to be done
        console.log(form);
    }
}

I've used this approach successfully in 4.1.0 and 4.1.1

like image 112
egerardus Avatar answered Oct 11 '22 18:10

egerardus