7-1. 内建
7-1-1. $scope
参考2-4. 作用域章节
7-1-2. $timeout
<!-- examples/services/timeout.html -->
<div>something happend after {{timeout}}s</div>
const app = new Highway({
$el: $('#app'),
$scope: {
timeout: 3
},
$mount() {
this.$timeout(() => {
alert('highway');
}, 3000);
}
});
7-1-2. $interval
<!-- examples/services/timeout.html -->
<div>something happend after {{timeout}}s</div>
const app = new Highway({
$el: $('#app'),
$scope: {
timeout: 3
},
$mount() {
this.$timeout(() => {
alert('highway');
}, 3000);
}
});
7-1-3. $http
复用jQuery/Zepto中的ajax方法
- http: .ajax
- get: .get
- post: .post
- json: .getJSON
- jsonp: .ajaxJSONP
- settings: .ajaxSettings
- settings:jQuery.ajaxSetup/ .ajaxSettings
<!-- examples/services/http.html -->
<ul>
<li hi-repeat="user in users">id: {{user.id}}, name: {{user.name}}</li>
</ul>
const app = new Highway({
$el: $('#app'),
$scope: {},
$mount() {
this.$http({
type: 'get',
url: './users.json',
success: (data, status, xhr) => {
this.$set('users', data.users)
},
error: (xhr, errorType, error) => {
alert('error');
}
})
}
});
7.1.4. $event
参阅6-3. 通信
7-2. 自定义
自定义服务是一个工厂函数
7-2-1. 入参
- $ctx: 当前上下文
7-2-2. 出参
可选。如返回,可通过this.$servcies[name]引用
$mount: 生命周期函数,挂载时调用
$unmount: 生命周期函数,销毁时调用
7-2-3. 全局
使用Highway.service定义,需指定宏服务名和服务工厂函数
7-2-4. 局部
指定视图中有效,通过$services指定,需指定宏指令名和宏指令工厂函数
7-2-5. 示例
定义一个cookie读写服务
<!-- examples/services/customized.html -->
<div id="app">
<button hi-on:click="clickMe">destroy me</button>
</div>
const cookie = function ({$ctx}) {
return $ctx.$cookie = {
$mount() {
console.log('>>> cookie services mounted')
},
$get(key) {
const reg = new RegExp(`(^| )${key}=([^;]*)(;|$)`);
const matches = document.cookie.match(reg);
if(matches) {
return matches[2]
}
},
$set(key, value) {
document.cookie = `${key}=${value}`;
},
$unmount() {
console.log('>>> cookie services unmounted')
},
destroy() {
this.$destory();
}
}
};
// 全局管道
//Highway.service('$cookie', cookie);
const app = new Highway({
$el: $('#app'),
$scope: {
ratio: 0.95
},
// 局部管道
$services: {
$cookie: cookie
},
$mount() {
this.$cookie.$set('cookie_0', 'highway');
this.$cookie.$set('cookie_1', 'hello world');
// 可通过$service引用
console.log('cookie_1 value is:' + this.$services['$cookie'].$get('cookie_1'));
},
clickMe() {
this.$destroy();
}
});