Learn the Publish-subscribe (Viewer) mode of JavaScript design patterns

Source: Internet
Author: User

1. Publish-Subscribe mode is also called the Observer pattern, which defines a one-to-many dependency between objects.

2. How to implement the Publish-subscribe mode

2-1. First specify a good publisher

2-2, add a buffer list to the publisher, the user holds the callback function to inform the Subscriber

2-3. When the last message is published, the Publisher will traverse the cache list and trigger the subscriber callback function

Example:

var salesOffice = {};
Salesoffice.clientlist = [];
Salesoffice.listen = function (KEY,FN) {
if (!this.clientlist[key]) {
This.clientlist[key] = [];
}
This.clientlist[key].push (FN);
}
Salesoffice.trigger = function () {
var key = Array.prototype.shift.call (arguments),
FNS = This.clientlist[key];
if (!fns | | fns.length = = 0) {
return false;
}
for (var i=0,fn; fn = fns[i++];) {
Fn.apply (this,arguments);
}
}

Salesoffice.listen (' S88 ', function (p) {
Console.log ("Price +" + p)
})

Salesoffice.listen (' s300 ', function (p) {
Console.log ("Price +" + p)
})

Salesoffice.trigger (' S88 ', 20000);
Salesoffice.trigger (' s300 ', 3000);

Common implementations of publish subscriptions:

Learn the Publish-subscribe (Viewer) mode of JavaScript design patterns

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.