Getting a refernce to an auto-instantiated Sencha Touch 2 view

梦想与她 提交于 2019-12-23 06:00:18

问题


I'd like to get a reference to my view from my Sencha Touch 2 controller, which looks like this (CoffeeScript):

Ext.define 'MyApp.view.Books',
    extend: 'Ext.Panel'
    id: 'books'
    config:
        html: 'Hello, Books!'
Ext.define 'MyApp.controller.Books',
    extend: 'Ext.app.Controller'
    views: [
        'Books'
    ]
    init: ->
        @control
            '#books':
                render: ->
                    console.log 'This is never called. Why?'
                show: ->
                    console.log 'This is called twice.'
                    # @getBooksView() is not a view instance, it is a class. Why?
                    console.log 'View class: ' + @getBooksView()?.$isClass
Ext.application
    name: 'MyApp'
    controllers: [
        'Books'
    ]
    launch: ->
        Ext.Viewport.setActiveItem
            xtype: 'booksview'

The 'Hello, Books' content appears (e.g. the component is rendered), but the render control handler is never even called. What am I doing wrong here?


回答1:


You shouln't use hardcoded id for any of the classes! You should be codding your view as:

Ext.define('MyApp.view.Books',{
    extend: 'Ext.Panel',
    alias : 'widget.books',
    config: {
        html: 'Hello, Books!'
    },
    initialize : function() {   
        // some init code etc..
        this.callParent();  
    }
});

Note the alias property. This helps you to get the reference of your view's instances. When you refer the view. Now in your controller you have:

...
this.control({
    'books' : {    
        render: function() {
            console.log('Render method called!');
        },
        show: function() {
            console.log('Show method called!');
        }

    },
    .
    ...

Note that you are not refering your view with the id property, instead through its alias or xtype. Now, if you need to access other controller's views or any other component in your controller, you can also make use of the refs system available. In this case, you will define the refs array in the controller definition as:

refs: [
    {ref: 'centerPane', selector: 'centerpane'}
],

Here the selector property is the value passed to Ext.ComponentQuery to get the component. So, you can get the instance of centerpane by:

this.getCenterPane();


来源:https://stackoverflow.com/questions/7799747/getting-a-refernce-to-an-auto-instantiated-sencha-touch-2-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!