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();
  }
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章