Object Model / Ember中的类模型

1.Objects in Ember

Ember中并没有广泛应用ES2015。

Javascript中不能动态的改变属相值,ember中用 Ember.Object 代替了原始的 object。

Ember还扩展了原始javasript中的 Array 属性,Ember.Enumerable。

同样,Ember 还扩展了 string 属性。

2.Class and instances 类和实例

2.1 Defining Classes

使用EmberObject.extend() 来定义class

使用 extend() 方法来创建一个类的子类。

2.2 重写父类的方法

通过调用this.super() 方法:

例如:

const Person = EmberObject.extend({

say(thing) {

alert(${this.get('name')} says: ${thing});

}

});

const Soldier = Person.extend({

say(thing) {

// this will call the method in the parent class (Person#say), appending

// the string ', sir!' to the variable thing passed in

this._super(${thing}, sir!);

}

});

let yehuda = Soldier.create({

name: 'Yehuda Katz'

});

yehuda.say('Yes');

2.3 向父类的方法传递参数

有时我们需要向父类的方法传递参数,使父类的方法可以正常运行。

比如常见的情况是重写 Embe-data 中的 normalizeResponse() 方法。

实现这一目的,一个方便快捷的方法是使用 spread operator ,就行 …arguments。

normalizeResponse(store, primaryModelClass, payload, id, requestType) {

//Customize my JSON payload for Ember-Data

return this._super(...arguments);

 …..

}

2.4创造实例

调用类的 create() 方法来创建一个类的实例。

创建实例时,可以在craete()中传入参数序列,例如:


 let Tom = person.craete({

 name: “Tom”,

 gender: “male”

 })

但是,在使用create() 时不能新建或改变类的方法。如果想要改变或者定义新的方法,就建立一个它的子类。

注意,一般使用大写开头的来定义类,比如Person,使用小写来定义类的实例,例如person 。

2.5 Init()

当一个新的实例被创建时,init() 方法会被自动调用。

需要注意的是,如果我们是继承了ember中底层类,比如 Ember.Component ,当我们重写init() 的时候,一定要调用 this.super(…arguments) 。如果没有调用的话,父类的方法就有可能不能正常运行,出现各种各样的错误。

2.6由同一个类定义的实例共享类的变量。

例如:

import EmberObject from '@ember/object';

const Person = EmberObject.extend({

 shoppingList: ['eggs', 'cheese']

});

Person.create({

 name: 'Stefan Penner',

 addItem() {

 this.get('shoppingList').pushObject('bacon');

 }

});

Person.create({

 name: 'Robert Jackson',

 addItem() {

 this.get('shoppingList').pushObject('sausage');

 }

});

Stefan Penner 和 Robert Jackson 两个实例中的shoppingList是一样的。

避免如此的做法是,在类中定义init()。

将 shoppingList 定义在 init() 中。

Init(){

 this.set(‘shoppingList’, [‘edge’,’cheese’];

}

2.7 改变实例中的属性

使用get() 和set() 方法,来访问和改变实例的属相值。

import EmberObject from '@ember/object';

const Person = EmberObject.extend({

name: 'Robert Jackson'

});

let person = Person.create();

person.get('name'); // 'Robert Jackson'

person.set('name', 'Tobias Fünke');

person.get('name'); // 'Tobias Fünke

3.Reopening 方法

3.1 reopening()

可以通过reoping() 方法来给一个已经定义好的类来增加一个新定义的变量。

除此之外,还能通过 reopening() 来重写一个类中存在的方法。

 Person.reopen({

 // override `say` to add an ! at the end

  say(thing) {

this._super(thing + '!');

}

});

3.2 reopenClass()

Person.reopenClass({

 isPerson: false

});

// override property of existing and future Person instances

Person.reopen({

 isPerson: true

});

Person.isPerson; // false - because it is static property created by `reopenClass`

Person.create().get('isPerson'); // true

4. 可计算的属性

详情请参考官方文档。

https://guides.emberjs.com/v3.1.0/object-model/computed-properties/

5.复杂的属性

5.1

有时候一个复杂的属性只有当向中增加数据时才会更新、删除、或者是奉更改。

我们可以是用 [] 来使属性在正确的时间更新。

例如:

import EmberObject, { computed } from '@ember/object';

import Component from '@ember/component';

export default Component.extend({

 todos: null,

 init() {

 this.set('todos', [

 EmberObject.create({ title: 'Buy food', isDone: true }),

 EmberObject.create({ title: 'Eat food', isDone: false }),

 EmberObject.create({ title: 'Catalog Tomster collection', isDone: true }),

 ]);

 },

 titles: computed('todos.[]', function() {

 let todos = this.get('todos');

 return todos.mapBy('title');

 })

});

5.2 @each

就像上边的代码中,当todos 中的某一条数据的 isDone 发生了变化,那么是不会引起页面的重新渲染的,但是我们希望isDone 的值发生变化时,页面能更新,我们可以使用@each 来解决这个问题。

import EmberObject, { computed } from '@ember/object';

import Component from '@ember/component';

export default Component.extend({

 todos: null,

 init() {

 this.set('todos', [

 EmberObject.create({ isDone: true }),

 EmberObject.create({ isDone: false }),

 EmberObject.create({ isDone: true }),

 ]);

 },

 incomplete: computed('todos.@each.isDone', function() {

 let todos = this.get('todos');

 return todos.filterBy('isDone', false);

 })

});

当然,@each 可以设置绑定为多个数据。

todos.@each.{priority,title}

5.3 computed.filterBy

筛选出符合的属性,返回一个数组。

import EmberObject, { computed } from '@ember/object';

import { filterBy } from '@ember/object/computed';

import Component from '@ember/component';

export default Component.extend({

 todos: null,

 init() {

 this.set('todos', [

 EmberObject.create({ isDone: true }),

 EmberObject.create({ isDone: false }),

 EmberObject.create({ isDone: true }),

 ]);

 },

 incomplete: filterBy('todos', 'isDone', false)

});

import TodoListComponent from 'app/components/todo-list';

let todoListComponent = TodoListComponent.create();

todoListComponent.get('incomplete.length');

// 1

6.Observers

6.1

Ember支持观察所有属性,包括复杂属性。

fullNameChanged: observer('fullName', function() {

 // deal with the change

 console.log(`fullName changed to: ${this.get('fullName')}`);

 })

Observer会监测属相值fullName, 一旦发生变化,log方法就会被执行。

6.2 在init时构建Observer

使用Ember.on

import EmberObject, { observer } from '@ember/object';

import { on } from '@ember/object/evented';

Person = EmberObject.extend({

 init() {

 this.set('salutation', 'Mr/Ms');

 },

 salutationDidChange: on('init', observer('salutation', function() {

 // some side effect of salutation changing

 }))

});

需要注意的是,没有使用的计算属性不会激活Observer。

Observer还可以在类的外边定义: 使用 addObserver()

person.addObserver('fullName', function() {

 // deal with the change

});

7.Bindings绑定

7.1 使用computed.alias() 来创建一个双向的绑定。

import EmberObject from '@ember/object';

import { alias } from '@ember/object/computed';

husband = EmberObject.create({

 pets: 0

});

Wife = EmberObject.extend({

 pets: alias('husband.pets')

});

wife = Wife.create({

 husband: husband

});

wife.get('pets'); // 0

// Someone gets a pet.

husband.set('pets', 1);

wife.get('pets'); // 1

7.2 computed.oneWay()单向绑定

import EmberObject, { computed } from '@ember/object';

import Component from '@ember/component';

import { oneWay } from '@ember/object/computed';

user = EmberObject.create({

 fullName: 'Kara Gates'

});

UserComponent = Component.extend({

 userName: oneWay('user.fullName')

});

userComponent = UserComponent.create({

 user: user

});

// Changing the name of the user object changes

// the value on the view.

user.set('fullName', 'Krang Gates');

// userComponent.userName will become "Krang Gates"

// ...but changes to the view don't make it back to

// the object.

userComponent.set('userName', 'Truckasaurus Gates');

user.get('fullName'); // "Krang Gates"

8. enumerables 枚举

详情请见官方文档:
https://guides.emberjs.com/v3.1.0/object-model/enumerables/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,657评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,889评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,057评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,509评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,562评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,443评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,251评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,129评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,561评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,779评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,902评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,621评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,220评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,838评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,971评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,025评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,843评论 2 354