三,angular2 for javascript 类 替代方案
angular2 for typesript官网文档中显示数据的章节讲到:"在真实的应用中,大多是到一个对象数组的绑定。要将此绑定转换成使用对象,需要把这个英雄名字数组变成Hero对象数组。但首先得有一个Hero类."
在使用angular2 for javascript 开发时,由于javascript 无法直接使用class关键词创建类,若要将
his.heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
转换为对象数组,这里可采用以下方法:
1,创建一个对象值为方法的对象, 用于代替类
2,采用调用对象的方法,来创建一个对象实例,用于传递参数
//app.component.js
(function(app) {
app.AppComponent = ng.core.Component({
selector: 'my-app',
//引入外部模板文件input.html
templateUrl:'input.html'
})
.Class({
constructor: function() {
this.title = 'our of Heroes';
this.heroes = [
// 2,采用调用对象的方法,来创建一个对象实例,用于传递参数
new this.Hero(1, 'chairmanmao'),
new this.Hero(2, 'Wxfeng'),
new this.Hero(3, 'ztguang'),
new this.Hero(4, 'asdfsdfsad')
];
this.myHero = this.heroes[0].name;
this.clickMessage = '';
this.values = '';
this.value = '';
},
//1,创建一个对象值为方法的对象, 用于代替类
Hero:function(id,name){
this.id = id;
this.name = name;
return this;
},
onClickMe:function(){
this.clickMessage = 'You are my hero!';
},
onKey:function(event) {
this.values += event.target.value + ' | ';
},
update:function(value) {
this.value = value;
}
});
})(window.app || (window.app = {}));
<!--input.html-->
<h1>{{title}}</h1>
<h2>My favorite hero is: {{myHero}}</h2>
<h3>循环输出:</h3>
<p>Heroes:</p>
<ul>
<!--读取heroes对象数组-->
<li *ngFor="let hero of heroes">
{{ hero.id }}
{{ hero.name }}
</li>
</ul>
<!--绑定到用户输入事件-->
<h3>绑定到用户输入事件:</h3>
<button (click)="onClickMe()">Click me!</button>
{{clickMessage}}
<!--通过 $event 对象取得用户输入-->
<h3>通过 $event 对象取得用户输入:</h3>
<input (keyup)="onKey($event)">
<p>{{values}}</p>
<!--从一个模板引用变量中获得用户输入-->
<h3>从一个模板引用变量中获得用户输入:</h3>
<input #box (keyup)="0">
<p>{{box.value}}</p>
<!--按键事件过滤(通过key.enter)-->
<h3>按键事件过滤(通过key.enter&&失去焦点):</h3>
<input #boxs (keyup.enter)="update(boxs.value)" (blur)="update(boxs.value)">
<p>{{value}}</p>
<!--失去焦点事件 (blur)-->


