Sencha Touch:数据包 – 模型Model

模型基本上是数据或字段的集合,分别用于存储某些特定类型的信息。

由于Sencha遵循基于基础的架构,因此可以自定义类以执行特定任务。

Ext.data.Model是定义任何模型时需要扩展的基类。

定义模型

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

Fields

字段用于存储一条信息,这些信息的集合称为模型。

我们主要在模型中定义以下类型的字段-

  • Integer
  • String
  • Boolean
  • Float

语法

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

Validators

在Sencha Touch中,模型支持许多验证,以使数据保持正确的格式。

以下是验证器-

  • Presence– 确保名称字段的值不为空。
  • Length – 限制字段的长度。它有两个参数-min和max-定义最小和最大长度。
  • Format – 确保字段值符合给定表达式。在以下示例中,不允许我们添加除数字之外的任何值。
  • Inclusion – 仅确保列表中定义的值。在下面的示例中,该值仅允许M和F。
  • Exclusion – 确保我们不允许在列表数组中定义的值。在以下示例中,它不允许使用零作为年龄。

语法

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

作者:terry,如若转载,请注明出处:https://www.web176.com/senchatouch/1626.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2021年1月22日 下午5:38
下一篇 2021年1月22日 下午5:54

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注