观察者模式

通过创建一个可观察的对象,当发生一个感兴趣的事件时将该事件通告给所有观察者,从而形成松散的耦合

订阅杂志

//发布者对象
var publisher = {
subscribers: {
any: [] //事件类型
},
//将订阅者添加到subscribers数组;
subscribe: function(fn, type) {
type = type || 'any';
if(typeof this.subscribers[type] === 'undefined') {
this.subscribers[type] = [];
}
this.subscribers[type].push(fn);
},
//从订阅者数组中删除订阅者
unsubscribe: function(fn, type) {
this.visitSubscribers('publish', publication, type);
},
//遍历循环
publish: function(publication, type) {
this.visitSubscribers('publish', publication, type);
},
visitSubscribers: function(action, arg, type) {
var pubtype = type || 'any',
subscribers = this.subscribers[pubtype], i, max = subscribers.length;
for(i = 0; i < max; i++) {
if(action === 'publish') {
subscribers[i](arg);
} else {
if(subscribers[i] === arg) {
subscribers.splice(i, 1);
}
}
}
}
}
//构造发行者
function makePublisher(o) {
var i;
for(i in publisher) {
if(publisher.hasOwnProperty(i) && typeof publisher[i] === 'function') {
o[i] = publisher[i];
}
}
o.subscribers = {any: []};
}
//paper对象,发布日刊和月刊
var paper = {
daily: function() {
this.publish("big news today");
},
monthly: function() {
this.publish("interesting analysis", "monthly");
}
};
//订阅者joe
var joe = {
drinkCoffee: function(paper) {
console.log('Just read ' + paper);
},
sundayPreNap: function(monthly) {
console.log('About to fall asleep reading this ' + monthly);
}
}
//将paper构造成一个发行者
makePublisher(paper);
//joe订阅paper
paper.subscribe(joe.drinkCoffee);
paper.subscribe(joe.sundayPreNap, 'monthly');
//触发事件
paper.daily();
paper.daily();
paper.daily();
paper.monthly();
//扩展将joe为发布者
makePublisher(joe);
joe.tweet = function(msg) {
this.publish(msg);
}
paper.readTweets = function(tweet) {
alert('Call big meeting! Someone ' + tweet);
}
joe.subscribe(paper.readTweets); joe.tweet('hated the paper today');

按键游戏

var publisher = {
subscribers: {
any: []
},
on: function (type, fn, context) {
type = type || 'any';
fn = typeof fn === "function" ? fn : context[fn];
if (typeof this.subscribers[type] === "undefined") {
this.subscribers[type] = [];
}
this.subscribers[type].push({fn: fn, context: context || this});
},
remove: function (type, fn, context) {
this.visitSubscribers('unsubscribe', type, fn, context);
},
fire: function (type, publication) {
this.visitSubscribers('publish', type, publication);
},
visitSubscribers: function (action, type, arg, context) {
var pubtype = type || 'any',
subscribers = this.subscribers[pubtype], i,
max = subscribers ? subscribers.length : 0; for (i = 0; i < max; i += 1) {
if (action === 'publish') {
subscribers[i].fn.call(subscribers[i].context, arg);
} else {
if (subscribers[i].fn === arg && subscribers[i].context === context) {
subscribers.splice(i, 1);
}
}
}
}
}; function makePublisher(o) {
var i;
for (i in publisher) {
if (publisher.hasOwnProperty(i) && typeof publisher[i] === "function") {
o[i] = publisher[i];
}
}
o.subscribers = {any: []};
} var game = {
keys: {},
addPlayer: function (player) {
var key = player.key.toString().charCodeAt(0);
this.keys[key] = player;
},
handleKeypress: function (e) {
e = e || window.event; // IE
if (game.keys[e.which]) {
game.keys[e.which].play();
}
},
handlePlay: function (player) {
var i, players = this.keys, score = {};
for (i in players) {
if (players.hasOwnProperty(i)) {
score[players[i].name] = players[i].points;
}
}
this.fire('scorechange', score);
}
}; function Player(name, key) {
this.points = 0;
this.name = name;
this.key = key;
this.fire('newplayer', this);
} Player.prototype.play = function () {
this.points += 1;
this.fire('play', this);
}; var scoreboard = {
element: document.getElementById('results'),
update: function (score) {
var i, msg = '';
for (i in score) {
if (score.hasOwnProperty(i)) {
msg += '<p><strong>' + i + '<\/strong>: ';
msg += score[i];
msg += '<\/p>';
}
}
this.element.innerHTML = msg;
}
}; makePublisher(Player.prototype);
makePublisher(game); Player.prototype.on("newplayer", "addPlayer", game);
Player.prototype.on("play", "handlePlay", game); game.on("scorechange", scoreboard.update, scoreboard); window.onkeypress = game.handleKeypress; var playername, key;
while (1) {
playername = prompt("Add player (name)");
if (!playername) {
break;
}
while (1) {
key = prompt("Key for " + playername + "?");
if (key) {
break;
}
}
new Player(playername, key);
}

javascript优化--12模式(设计模式)03的更多相关文章

  1. javascript优化--11模式(设计模式)02

    策略模式 在选择最佳策略以处理特定任务(上下文)的时候仍然保持相同的接口: //表单验证的例子 var data = { firs_name: "Super", last_name ...

  2. javascript优化--10模式(设计模式)01

    单体模式:保证一个特定类仅有一个实例;即第二次使用同一个类创建新对象时,应该得到与第一个所创建对象完全相同对象: 在JS中,可以认为每次在使用对象字面量创建对象的时候,实际上就在创建一个单体: 当使用 ...

  3. javascript优化--13模式1(DOM和浏览器模式)

    注意分离: 通过将CSS关闭来测试页面是否仍然可用,内容是否依然可读: 将JavaScript关闭来测试页面仍然可以执行正常功能:所有连接是否正常工作:所有的表单是否可以正常工作: 不使用内联处理器( ...

  4. javascript优化--08模式(代码复用)01

    优先使用对象组合,而不是类继承: 类式继承:通过构造函数Child()来获取来自于另一个构造函数Parent()的属性: 默认模式:子类的原型指向父类的一个实例 function inherit(C, ...

  5. javascript优化--06模式(对象)01

    命名空间: 优点:可以解决命名混乱和第三方冲突: 缺点:长嵌套导致更长的查询时间:更多的字符: 通用命名空间函数: var MYAPP = MYAPP || {}; MYAPP.namespace = ...

  6. javascript优化--05模式(函数)

    回调函数模式: 基本例子: var findNodes = function (callback) { ...................... if (typeof callback !== ' ...

  7. javascript优化--14模式2(DOM和浏览器模式)

    远程脚本 XMLHttpRequest JSONP 和XHR不同,它不受同域的限制: JSONP请求的可以是任意的文档: 请求的URL通常格式为http://example.js?calback=Ca ...

  8. javascript优化--09模式(代码复用)02

    原型继承 ://现代无类继承模式 基本代码: var parent = { name : "Papa" } var child = object(parent); function ...

  9. javascript优化--07模式(对象)02

    沙箱模式: 解决空间命名模式的几个缺点: 命名空间模式中无法同时使用一个应用程序或库的两个版本运行在同一个页面中,因为两者需要相同的全局符号: 以点分割,需要输入更长的字符,解析时间也更长: 全局构造 ...

随机推荐

  1. 【leetcode】Isomorphic Strings(easy)

    Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the chara ...

  2. $.each 和$(selector).each()的区别

    $.each() 对数组或对对象内容进行循环处理 jQuery.each( collection, callback(indexInArray, valueOfElement) ) collectio ...

  3. Java IO流总结

    Java IO流分类以及主要使用方式如下: IO流 |--字节流 |--字节输入流 InputStream: int read();//一次读取一个字节 int read(byte[] bys);// ...

  4. JAVA addShutdownHook测试

    public static void main(String[] args) { System.out.println("1111111111"); try { Thread.sl ...

  5. pmap

    .[root@localhost security]# pmap -d : -bash Address Kbytes Mode Offset Device Mapping r-x-- : bash b ...

  6. maven入门基础(转)

    maven介绍 maven是构建工具,也是构建管理工具.ant只是构建工具,因为不支持生成站点功能,只有预处理,编译,打包,测试,部署等功能. maven坐标 groupId:项目组织的逆向域名,比如 ...

  7. JavaScript基础——处理字符串

    String对象是迄今为止在JavaScript中最常用的对象.在你定义一个字符串数据类型的变量的任何时候,JavaScript就自定为你创建一个String对象.例如: var myStr = &q ...

  8. VS2012/2013 停止调试后,无法刷新页面

  9. ARPPING

    http://www.tuicool.com/articles/M7B3umj http://lixcto.blog.51cto.com/4834175/1571838/

  10. 【JAVA线程间通信技术】

    之前的例子都是多个线程执行同一种任务,下面开始讨论多个线程执行不同任务的情况. 举个例子:有个仓库专门存储货物,有的货车专门将货物送往仓库,有的货车则专门将货物拉出仓库,这两种货车的任务不同,而且为了 ...