先记住这段话,不一定马上理解,看完了代码回过来再看。ember 在得到
name
和timer
属性的值后会把数据插入路由(ApplicationRoute)
控制器(controller)
的model
属性中。
第一个路由和如何通过model
提供数据给模版
2.1、路由
每一个ember的应用程序都有路由。 路由就是用户在点击网页上的链接后,页面切换不同模版时地址栏里显示的不同路径,例如/about
与 /products/1
,这个说法不太严谨,但有益于入门理解,当你像第一节课 创建一个命名空间后 ember就会寻找application
的 ApplicationRoute
,没有的话它会自己建一个,作为根目录。
2.2、Route::model
方法
这次我们要自己定义一个路由,并且为路由定义一个模型 告诉路由要引用的数据。第一课的例子中数据是通过一个函数绑定到模版,这不是一个好的方法,事实上一个路由可以定义一个数据模型,当访问路径是自动调用,然后发送到此对象的对应模版,显示相关内容。
创建一个路由,定义路由用到的模型,数据模型意思是返回App
对象的 name
属性值
var App = Ember.Application.create();
App.ApplicationRoute = Ember.Route.extend({
model: function() {
return {name: 'My App'}
}
});
对应模版内容为:
<h1>{{name}}</h1>
2.3 Ember 的对象模型
所有的对象都继承自Ember.Object
, 我们定于的路由ApplicationRoute
是Ember.Route
的扩展,或者说继承于Ember.Route
, 可以把Ember.Route 看作是类,创建和调用的`ApplicationRoute``是一个实例 或子类。 这些在ember 里通过少量的语句就可以完美实现。
2.4、 Route::activate and Route::deactivate 定义路由的动作的方法
当进出一个路由,往往会有些特定的动作,这些动作改变会模型数据,我们通过secondsonpage 计时器的例子来看下效果。
首先模型提供的数据有两个:name和timer
<h1>{{name}}</h1>
<h2>{{timer}}</h2>
定义路由和模型后,定义一个动作,用来改变数据模型,由于数据绑定到模版,可以看到模型数据在不断变化。
var App = Ember.Application.create();
App.ApplicationRoute = Ember.Route.extend({
model: function() {
//模型提供了两个显示到模版的数据,name和time
return {
name: 'My App',
timer: 0
}
},
//activate 定义了一个动作,不断改变模型里的timer的值
activate: function() {
this.interval = setInterval(function() {
//在程序里引用timer时通过默认的 控制器.模型.timer 的方式 即 controller.model.timer 这个需要注意下,之所以这样写,看看文章开始的那句话就明白了;
//好话说二遍:ember 在得到`name`和`timer` 属性的值后会把数据插入路由(ApplicationRoute)控制器(controller)的model属性中。
var timer = this.get('controller.model.timer');
this.set('controller.model.timer', timer + 1);
}.bind(this), 1000);
},
// 定义另一个清零的动作,在执行到timer 增加到1000后重新设置为0。
deactivate: function() {
clearInterval(this.interval);
}
});
2.5 完整代码
<!DOCTYPE html>
<!--
Created using JS Bin
http://jsbin.com
Copyright (c) 2016 by symphonyh (http://jsbin.com/gugowiw/1/edit)
Released under the MIT license: http://jsbin.mit-license.org
-->
<meta name="robots" content="noindex">
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0-rc.3/handlebars.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/ember.js/1.0.0-rc.1/ember.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<script type="text/x-handlebars">
<h1>{{name}}</h1>
<h2>{{timer}}</h2>
</script>
<script id="jsbin-javascript">
var App = Ember.Application.create();
App.ApplicationRoute = Ember.Route.extend({
model: function() {
return { name: 'My App', timer: 0 };
},
activate: function() {
this.interval = setInterval(function() {
var timer = this.get('controller.model.timer');
this.set('controller.model.timer', timer + 1);
}.bind(this), 1000);
},
deactivate: function() {
clearInterval(this.interval);
}
});
</script>
</body>
</html>
全文完。