javascript优化--12模式(设计模式)03
观察者模式
通过创建一个可观察的对象,当发生一个感兴趣的事件时将该事件通告给所有观察者,从而形成松散的耦合
订阅杂志
//发布者对象
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的更多相关文章
- javascript优化--11模式(设计模式)02
策略模式 在选择最佳策略以处理特定任务(上下文)的时候仍然保持相同的接口: //表单验证的例子 var data = { firs_name: "Super", last_name ...
- javascript优化--10模式(设计模式)01
单体模式:保证一个特定类仅有一个实例;即第二次使用同一个类创建新对象时,应该得到与第一个所创建对象完全相同对象: 在JS中,可以认为每次在使用对象字面量创建对象的时候,实际上就在创建一个单体: 当使用 ...
- javascript优化--13模式1(DOM和浏览器模式)
注意分离: 通过将CSS关闭来测试页面是否仍然可用,内容是否依然可读: 将JavaScript关闭来测试页面仍然可以执行正常功能:所有连接是否正常工作:所有的表单是否可以正常工作: 不使用内联处理器( ...
- javascript优化--08模式(代码复用)01
优先使用对象组合,而不是类继承: 类式继承:通过构造函数Child()来获取来自于另一个构造函数Parent()的属性: 默认模式:子类的原型指向父类的一个实例 function inherit(C, ...
- javascript优化--06模式(对象)01
命名空间: 优点:可以解决命名混乱和第三方冲突: 缺点:长嵌套导致更长的查询时间:更多的字符: 通用命名空间函数: var MYAPP = MYAPP || {}; MYAPP.namespace = ...
- javascript优化--05模式(函数)
回调函数模式: 基本例子: var findNodes = function (callback) { ...................... if (typeof callback !== ' ...
- javascript优化--14模式2(DOM和浏览器模式)
远程脚本 XMLHttpRequest JSONP 和XHR不同,它不受同域的限制: JSONP请求的可以是任意的文档: 请求的URL通常格式为http://example.js?calback=Ca ...
- javascript优化--09模式(代码复用)02
原型继承 ://现代无类继承模式 基本代码: var parent = { name : "Papa" } var child = object(parent); function ...
- javascript优化--07模式(对象)02
沙箱模式: 解决空间命名模式的几个缺点: 命名空间模式中无法同时使用一个应用程序或库的两个版本运行在同一个页面中,因为两者需要相同的全局符号: 以点分割,需要输入更长的字符,解析时间也更长: 全局构造 ...
随机推荐
- assign() 方法
assign() 方法可加载一个新的文档. 语法 location.assign(URL) <html> <head> <script type="text/j ...
- 【XLL API 函数】xlSet
快速的将常数值放入到单元格区域中. 原型 Excel12(xlSet, LPXLOPER12 pxRes, 2, LPXLOPER12 pxReference,LPXLOPER pxValue); 参 ...
- php面向对象加载类、常用设计模式
加载类: include("./Ren.class.php"); include "./Ren.class.php"; 用此方法的时候include后面要加空格 ...
- js中masonry与infinitescroll结合 形成瀑布流
后台:(有点问题 page应该从1开始 而不是从0开始) public function actionExperts() { $top=5; $page=em ...
- CString 操作
CString Left( int nCount ) const; //从左边1开始获取前 nCount 个字符 CString Mid( int nFirst ) ...
- $(inherited) "$(SRCROOT) 修改.a文件的路径 --Library Search Paths
$(inherited) "$(SRCROOT)/.a文件所在的文件名" //如果有多个.a文件格式就像这样 $(inherited) "$(SRCROOT)/xxxx& ...
- 22中编程语言的HelloWorld
C:printf("HelloWorld"); C++ : cout<<"HelloWorld"; QBasic : Print "Hel ...
- 数据结构One_Vector(向量的简单实现)
#include <iostream> using namespace std; template<typename Object> class Vector { privat ...
- SQL语句删除重复数据
1.如表中没有主键,先添加自动增长主键 alter table 表名 add 列名 int identity (1,1) primary key 2.删除重复数据 delete from 表名 whe ...
- Linux常用的日志分析命令与工具
>>基础命令 操作 命令 说明 查看文件的内容 cat -n access.log -n显示行号 分页显示文件 more access.log Enter下一行,空格下一页,F下一屏,B上 ...