Sencha Touch - 控制器



控制器是 MVC 架构的主要组件之一。

控制器是控制功能的组件。我们在控制器中编写监听器,它充当视图和模型之间的粘合剂,其中视图用于视觉 UI,而模型用于存储和操作数据。

控制器的主要功能有:

  • 操作在控制器中编写,例如,如果我们在应用程序中按下按钮或将鼠标悬停在某个链接上,则将在控制器监听器函数中编写要执行的操作。

  • 控制器提供了 init 和 launch 函数,它们在应用程序和控制器启动时被调用。

控制器 Init 和 Launch 函数

我们可以在控制器中定义 launch 和 init 函数。应用程序可以有自己的 launch 函数,因此以下是函数应该被调用的顺序。

  • 应用程序启动时首先调用控制器的 Init 函数。

  • 然后调用应用程序的 launch 函数。

  • 在应用程序的 launch 函数被调用并且应用程序启动后,将调用控制器的 launch 函数。

控制器的 Config 组件

我们可以在控制器的 config 中使用 refs 和 control。让我们看看两者是如何工作的。

Refs

Refs 在 config 中的使用方式如下例所示。

Ext.define('MyApp.controller.Main', {
   extend: 'Ext.app.Controller', config: {
      refs: {
         tab: '#divId
      }
   },

   addLogoutButton: function() {
      this.getTab().add({
         text: 'Logout'
      });
   }
});

Refs 可以用来引用任何 id。如上例所示,tab 是创建的 ref,它引用了 id #divId。

Refs 以键值对的形式创建,如上例所示,tab 是键,divId 是值。每当创建一个 ref 时,都会自动为其创建 getter 和 setter。在上例中,我们创建了一个名为 tab 的 ref,因此我们可以通过 getTab 方法访问它,该方法是自动创建的。

Control

Control 是一种与 ref 类似的 config,它以 ref 作为键,以 listen 函数作为值,该函数被调用以执行某些任务。

Ext.define('MyApp.controller.Main', {
   extend: 'Ext.app.Controller', config: {
      control: {
         loginButton: {
            tap: 'doLogin'
            // ref tap is the key and doLogin is the value which is a listener.
         }
      },

      refs: {
         loginButton: 'button[action=login]' 
      }
   },

   doLogin: function() {
      // called whenever the Login button is tapped
   }
});

路由

控制器定义了它感兴趣的路由。借助路由,我们可以将应用程序的任何部分链接到提供的路由。

Ext.define('MyApp.controller.Main', {
   extend: 'Ext.app.Controller', config: {
      routes: {
         login: 'showLogin',
		 'user/:id': 'userId'
      }
   },

   showLogin: function() {
      // statements
   },
   userId: function() {
      // statements
   }
});

路由可以通过浏览器的地址栏 URL 访问。

在上例中,如果用户访问 URL https://myApp.com/#login,则将调用 showLogin 控制器函数。

路由也可以使用通配符,例如,如果浏览器 URL 为 https://myApp.com/#user/3003,则将调用 userId 函数。

因此,每当浏览器 URL 更改时,路由都会自动调用特定的控制器函数。

sencha_touch_core_concepts.htm
广告

© . All rights reserved.