观察者模式

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

订阅杂志

//发布者对象
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. JS里设定延时:js中SetInterval与setTimeout用法

     js中SetInterval与setTimeout用法 JS里设定延时: 使用SetInterval和设定延时函数setTimeout 很类似.setTimeout 运用在延迟一段时间,再进行某项操 ...

  2. osg四元数设置roll pitch heading角度

    roll绕Y轴旋转 pitch绕X轴旋转 heading绕Z轴旋转 单位是弧度,可以使用osg::inDegrees(45)将45角度转换为弧度 定义一个四元数 osg::Quat q( roll,o ...

  3. September 1st 2016 Week 36th Thursday

    Everything is going on, but don't give up trying. 万事随缘,但不要放弃努力. There are numerous things that we ca ...

  4. nmake geos

    参考:http://blog.sina.com.cn/s/blog_82a2a7d301010f87.html 1 打开visual  studio command prompt 该工具位于 开始程序 ...

  5. iOS开发系列--Objective-C 之 KVC、KVO

    概述 由于ObjC主要基于Smalltalk进行设计,因此它有很多类似于Ruby.Python的动态特性,例如动态类型.动态加载.动态绑定等.今天我们着重介绍ObjC中的键值编码(KVC).键值监听( ...

  6. 对于类的双重调用的demo

    代码如下: package cao.com.duixiang; public class TestCCircle { public static void main(String[] args) { ...

  7. JNDI 和JDBC的区别

    1.JNDI 和JDBC的区别和联系.两者都是API,是一个标准.并不是什么产品或方法.JDBC 全称:Java Database Connectivity 以一种统一的方式来对各种各样的数据库进行存 ...

  8. IPC进程通信机制

    select.poll.epoll之间的区别总结[整理] 进程间通信---共享内存 信号量和互斥锁的区别 http://www.2cto.com/os/201510/445553.html http: ...

  9. NYOJ题目112指数运算

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAs0AAAIICAIAAAAaCETRAAAgAElEQVR4nO3drW7jWtwv4PcmwnMhxb ...

  10. Genymotion

    @Genymotion相关文件下载地址 http://pan.baidu.com/s/1nu9nReh @虚拟机网络代理设置 Normal 0 7.8 磅 0 2 false false false ...