3.1. The Publisher-Subscriber Pattern (ok)

Có chỉnh sửa để dễ hiểu hơn :)

[en]
Looked  at the pubsub pattern
Communication takes place over a named channel
Based on callbacks which are triggered when events occur
Can pass data to callback
A dispose method can be used to unsubscribe from events
Main advantage of pubsub is loose coupling
But that can obsource the relationships between modules
[vi]
Đã nhìn vào mẫu pubsub
Giao tiếp diễn ra trên một kênh được đặt tên
Dựa trên các lệnh gọi lại được kích hoạt khi các sự kiện xảy ra
Có thể chuyển dữ liệu để gọi lại
Phương pháp hủy bỏ có thể được sử dụng để hủy đăng ký sự kiện
Ưu điểm chính của pubsub là khớp nối lỏng lẻo
Nhưng điều đó có thể che khuất mối quan hệ giữa các mô-đun

C:\xampp\htdocs\php\index.html

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <meta charset="utf-8" />
  <title>Put JavaScript Design Patterns into Practice</title>
  <style>
  	html, body { background: #faf6eb; margin: 0; } header { font-family: 'Adelle Basic'; font-weight: bold; } header img { margin: 30px 60px; float: left; } hgroup { float: left; } h1 { margin-top: 45px; margin-bottom: 0; } h2 { margin-top: 10px; font-size: 16px; } .right { position: fixed; bottom: 30px; right: 30px; }
  </style>
</head>
<body>
  <header>
    <img src="img/logo.png" />
    <hgroup>
      <h1>Put JavaScript Design Patterns into Practice</h1>
      <h2>by Dan Wellman</h2>
    </hgroup>
  </header>
  <img class="right" src="img/books.gif" />
  <script data-main="js/main" src="bower_components/requirejs/require.js"></script>
</body>
</html>

C:\xampp\htdocs\php\js\main.js

require(['pubsub/init'],function(init) {
	var examples = {
		pubsub: init
	}
	for (var example in examples) {
		examples[example].init();
	}
});

C:\xampp\htdocs\php\js\pubsub\init.js

define(function(require) {
  'use strict';
  return {
    init: function() {
      var moduleA = require('pubsub/moduleA');
      var moduleB = require('pubsub/moduleB');
      moduleB.publishEvent();
    }
  };
});

C:\xampp\htdocs\php\js\pubsub\pubsub.js

define(function() {
  'use strict';
  var subscribers = {};
  return {
    publish: function(topic, data) {
      if (!subscribers[topic]) {
        return;
      }
      console.log(subscribers[topic][0](data));
    },
    subscribe: function(topic, callback) {
      if (!subscribers[topic]) {
        subscribers[topic] = [];
      }
      subscribers[topic].push(callback);
    }
  };
});

C:\xampp\htdocs\php\js\pubsub\moduleA.js

define(function(require) {
  'use strict';
  var pubSub = require('pubsub/pubsub');
  pubSub.subscribe('atopic', function(data) {
  	return data.something;
  });
});

C:\xampp\htdocs\php\js\pubsub\moduleB.js

define(function(require) {
  'use strict';
  var pubSub = require('pubsub/pubsub');
  return {
    publishEvent: function() {
      var data = {
        something: 'some data'
      };
      pubSub.publish('atopic', data);
    }
  };
});

Last updated

Navigation

Lionel

@Copyright 2023