Загрузить другое представление после входа в систему с помощью sencha touch 2.0

У меня глупая проблема, и я бы хотел, чтобы вы мне помогли. Заранее спасибо.

Ситуация следующая: у меня есть 2 вида (оба созданы с помощью sencha architect 2.0), один для входа в систему, а другой для общих целей. И я хотел бы загрузить второе представление об успешном ответе при попытке входа в систему, то есть после любого успешного входа в систему. Основная проблема заключается в том, что я пробовал с Ex.create, Ext.Viewport.add, Ext.Viewport.setActiveItem, но мне не удается отобразить второе представление на экране, экран входа просто остается там, а приложение не загружает другое представление. Другое дело, мне не нужно использовать для этого навигационное представление.

Вот код моего контроллера, из которого я хочу загрузить свой второй вид. И, как вы увидите, я даже создал ссылку на представление с включенным автосозданием и идентификатором «mainTabPanel»:

Ext.define('MyApp.controller.Login', {
extend: 'Ext.app.Controller',
config: {
    refs: {
        loginButton: {
            selector: '#login',
            xtype: 'button'
        },
        username: {
            selector: '#user',
            xtype: 'textfield'
        },
        password: {
            selector: '#pass',
            xtype: 'passwordfield'
        },
        mainTabPanel: {
            selector: '#mainTabPanel',
            xtype: 'tabpanel',
            autoCreate: true
        }
    },

    control: {
        "loginButton": {
            tap: 'onLoginButtonTap'
        }
    }
},

onLoginButtonTap: function(button, e, options) {
    Ext.Ajax.request({
        url: '../../backend/auth.php',

        method: 'POST',

        params: {
            user: this.getUsername().getValue(),
            pass: this.getPassword().getValue()
        },

        success: function(response) {
            var json = Ext.decode(response.responseText);
            if (json.type == 'success') {
                // LOAD THE DAMN SECOND VIEW HERE!
                //var paneltab = Ext.create('MyApp.view.MainTabPanel');
                //Ext.Viewport.add(paneltab);
                //Ext.Viewport.setActiveItem(this.getMainTabPanel());
            } else {
                alert(json.value);
            }
        },

        failure: function(response) {
            alert('The request failed!');
        }
    });
}
});

И вот код моего входа в систему:

Ext.define('MyApp.view.LoginForm', {
extend: 'Ext.form.Panel',

config: {
    id: 'loginForm',
    ui: 'light',
    items: [
        {
            xtype: 'fieldset',
            ui: 'light',
            title: 'Log into the system',
            items: [
                {
                    xtype: 'textfield',
                    id: 'user',
                    label: 'User',
                    name: 'user'
                },
                {
                    xtype: 'passwordfield',
                    id: 'pass',
                    label: 'Pass',
                    name: 'pass'
                }
            ]
        },
        {
            xtype: 'button',
            id: 'login',
            ui: 'confirm',
            text: 'Login'
        }
    ]
}
});

И, наконец, код представления, которое я хочу загрузить. Этот вид загружается нормально, если я устанавливаю его как начальный вид, но не загружается при успешном входе в систему:

Ext.define('MyApp.view.MainTabPanel', {
extend: 'Ext.tab.Panel',

config: {
    id: 'mainTabPanel',
    layout: {
        animation: 'slide',
        type: 'card'
    },
    items: [
        {
            xtype: 'container',
            layout: {
                type: 'vbox'
            },
            title: 'Tab 1',
            iconCls: 'time',
            items: [
                {
                    xtype: 'titlebar',
                    docked: 'top',
                    title: 'General Report',
                    items: [
                        {
                            xtype: 'button',
                            iconCls: 'refresh',
                            iconMask: true,
                            text: '',
                            align: 'right'
                        }
                    ]
                },
                {
                    xtype: 'container',
                    height: 138,
                    flex: 1,
                    items: [
                        {
                            xtype: 'datepickerfield',
                            label: 'From',
                            placeHolder: 'mm/dd/yyyy'
                        },
                        {
                            xtype: 'datepickerfield',
                            label: 'To',
                            placeHolder: 'mm/dd/yyyy'
                        },
                        {
                            xtype: 'numberfield',
                            label: 'Hours'
                        }
                    ]
                },
                {
                    xtype: 'dataview',
                    ui: 'dark',
                    itemTpl: [
                        '<div style="height:50px; background-color: white; margin-bottom: 1px;">',
                        '    <span style="color: #0000FF">{user}</span>',
                        '    <span>{description}</span>',
                        '</div>'
                    ],
                    store: 'hoursStore',
                    flex: 1
                }
            ]
        },
        {
            xtype: 'container',
            title: 'Tab 2',
            iconCls: 'maps'
        },
        {
            xtype: 'container',
            title: 'Tab 3',
            iconCls: 'favorites'
        }
    ],
    tabBar: {
        docked: 'bottom'
    }
}
});

Пожалуйста, мне нужна помощь... :) Я застрял здесь уже как 3 дня и не могу понять, в чем проблема. Спасибо.


person Holland Salazar    schedule 08.06.2012    source источник


Ответы (3)


Не могли бы вы также опубликовать свой app.js? Я пробую ваш код здесь, и он загружает представление, как и ожидалось. Вот мой app.js:

Ext.application({
    name: 'MyApp',

    requires: [
        'Ext.MessageBox'
    ],
    controllers: ['Login'],
    views: ['LoginForm','MainTabPanel'],

    icon: {
        '57': 'resources/icons/Icon.png',
        '72': 'resources/icons/Icon~ipad.png',
        '114': 'resources/icons/[email protected]',
        '144': 'resources/icons/[email protected]'
    },

    isIconPrecomposed: true,

    startupImage: {
        '320x460': 'resources/startup/320x460.jpg',
        '640x920': 'resources/startup/640x920.png',
        '768x1004': 'resources/startup/768x1004.png',
        '748x1024': 'resources/startup/748x1024.png',
        '1536x2008': 'resources/startup/1536x2008.png',
        '1496x2048': 'resources/startup/1496x2048.png'
    },

    launch: function() {
        // Destroy the #appLoadingIndicator element
        Ext.fly('appLoadingIndicator').destroy();

        // Initialize the main view
        //Ext.Viewport.add(Ext.create('MyApp.view.Main'));
        Ext.Viewport.add(Ext.create('MyApp.view.LoginForm'));
    },

    onUpdated: function() {
        Ext.Msg.confirm(
            "Application Update",
            "This application has just successfully been updated to the latest version. Reload now?",
            function(buttonId) {
                if (buttonId === 'yes') {
                    window.location.reload();
                }
            }
        );
    }
});
person alamaby    schedule 10.09.2012

Уничтожьте панель входа, она вам больше не нужна...

success: function(response) {
        var json = Ext.decode(response.responseText);

        if (json.type == 'success') {
            // LOAD THE DAMN SECOND VIEW HERE!
            var paneltab = Ext.create('MyApp.view.MainTabPanel');
            Ext.getCmp('loginForm').destroy();
            Ext.Viewport.add(paneltab);

        } else {
            alert(json.value);
        }
    },
person Alex    schedule 08.06.2012

Здесь есть несколько проблем:

  • В вашем правиле autoCreate используется xtype: 'tabpanel', который будет создавать только ванильный Ext.TabPanel без элементов в нем. Вам нужно будет назначить атрибут xtype для MyApp.view.MainTabPanel, например xtype: 'mainTabPanel', а затем использовать это значение xtype в своем правиле автоматического создания.

  • Это объясняет, почему этот код не будет работать, так как this.getMainTabPanel() вернет неправильный объект. Проще было бы просто использовать Ext.Viewport.setActiveItem(paneltab).

    • In general, you usually don't want assign an id to a view (id: 'mainTabPanel'). Safer to just use an xtype to fetch it. Although you don't need it in this case, avoiding global id's allows you to create multiple instances of a view (or any other class type).
person Tony O'Hagan    schedule 23.11.2013