如果提示找不到filter或者forEach函数,可能是因为你的浏览器还不够新,暂时不支持新标准的函数,你可以使用如下方式自己定义: 复制代码 代码如下: if (!Array.prototype.forEach) { Array.prototype.forEach = function (fn, thisObj) { var scope = thisObj || window; for (var i = 0, j = this.length; i < j; ++i) { fn.call(scope, this[i], i, this); } }; } if (!Array.prototype.filter) { Array.prototype.filter = function (fn, thisObj) { var scope = thisObj || window; var a = []; for (var i = 0, j = this.length; i < j; ++i) { if (!fn.call(scope, this[i], i, this)) { continue; } a.push(this[i]); } return a; }; }
版本三 如果想让多个对象都具有观察者发布订阅的功能,我们可以定义一个通用的函数,然后将该函数的功能应用到需要观察者功能的对象上,代码如下: 复制代码 代码如下: //通用代码 var observer = { //订阅 addSubscriber: function (callback) { this.subscribers[this.subscribers.length] = callback; }, //退订 removeSubscriber: function (callback) { for (var i = 0; i < this.subscribers.length; i++) { if (this.subscribers[i] === callback) { delete (this.subscribers[i]); } } }, //发布 publish: function (what) { for (var i = 0; i < this.subscribers.length; i++) { if (typeof this.subscribers[i] === "function") { this.subscribers[i](what); } } }, // 将对象o具有观察者功能 make: function (o) { for (var i in this) { o[i] = this[i]; o.subscribers = []; } } };
然后订阅2个对象blogger和user,使用observer.make方法将这2个对象具有观察者功能,代码如下: 复制代码 代码如下: var blogger = { recommend: function (id) { var msg = "dudu 推荐了的帖子:" + id; this.publish(msg); } };
var user = { vote: function (id) { var msg = "有人投票了!ID=" + id; this.publish(msg); } };
observer.make(blogger); observer.make(user);
使用方法就比较简单了,订阅不同的回调函数,以便可以注册到不同的观察者对象里(也可以同时注册到多个观察者对象里): 复制代码 代码如下: var tom = { read: function (what) { console.log("Tom看到了如下信息:" + what) } };
var mm = { show: function (what) { console.log("mm看到了如下信息:" + what) } }; // 订阅 blogger.addSubscriber(tom.read); blogger.addSubscriber(mm.show); blogger.recommend(123); //调用发布