Sencha Touch - 模型



模型基本上是資料的集合或欄位,每個欄位用於儲存某種特定型別的資訊。

由於 Sencha 遵循基於基礎的架構,因此可以自定義類以執行特定任務。

Ext.data.Model 是我們定義任何模型時需要擴充套件的基類。

定義模型

Ext.define('Student', {
   extend: 'Ext.data.Model', config: {
      fields: [
         { name: 'id', type: 'int' },
         { name: 'name', type: 'string' }
      ]
   }
});

欄位

欄位用於儲存資訊片段,欄位的集合稱為模型。

我們主要在模型中定義以下型別的欄位:

  • 整數
  • 字串
  • 布林值
  • 浮點數

語法

{ name: 'id', type: 'int' },
{ name: 'name', type: 'string' },
{ name: 'marks', type: Float },
{ name: 'newStudent', type: 'boolean' }

驗證器

在 Sencha Touch 中,模型支援多種驗證方式,以確保資料格式正確。

以下是驗證器:

  • 存在性 - 確保名稱欄位沒有空值。

  • 長度 - 限制欄位的長度。它有兩個引數 - min 和 max - 定義最小和最大長度。

  • 格式 - 確保欄位值符合給定的表示式。在以下示例中,它不允許我們新增任何數字以外的值。

  • 包含 - 確保只允許列表中定義的值。在以下示例中,它只允許 M 和 F 作為值。

  • 排除 - 確保我們不允許列表陣列中定義的值。在以下示例中,它不允許零作為年齡。

語法

validations: [
   { type: validation type,  field: on which the validation has to applied }
]
validations: [
   { type: 'presence',  field: 'name' },
   { type: 'length',    field: 'name', min: 5 },
   { type: 'format',    field: 'age', matcher: /\d+/ },
   { type: 'inclusion', field: 'gender', list: ['male', 'female'] },
   { type: 'exclusion', field: 'name', list: ['admin'] }
],

// now lets try to create a new user with as many validation errors as we can
var newUser = Ext.create('User', {
   name: 'admin', age: 'twenty-nine', gender: 'not a valid gender'
});

// run some validation on the new user we just created
var errors = newUser.validate();

console.log('Is User valid?', errors.isValid()); 
// returns 'false' as there were validation errors

console.log('All Errors:', errors.items); 
// returns the array of all errors found on this model instance

console.log('Age Errors:', errors.getByField('age')); // returns the errors for the age field
sencha_touch_data.htm
廣告
© . All rights reserved.