7. 服务 -- Highway MVVM

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();
  }
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值