function Observer() {
this.fns = [];
}
Observer.prototype = {
subscribe : function(fn) {
this.fns.push(fn);
},
unsubscribe : function(fn) {
this.fns = this.fns.filter(
function(el) {
if ( el !== fn ) {
return el;
}
}
);
},
fire : function(o, thisObj) {
var scope = thisObj || window;
this.fns.forEach(
function(el) {
el.call(scope, o);
}
);
}
};
var fn = function() {};
var o = new Observer;
o.subscribe(fn);
o.fire('here is my data');
o.unsubscribe(fn);
我无法理解这背后的整个概念。我想在我的项目中实现此模式。我有一个表单提交视图,它调用 Web 服务并返回我的响应。
如果我必须在我的项目中实现这一点,这是一个简单的请求和响应......我该怎么做?我知道您在有变化时通知您的观察员...假设我向我的 API 发出请求并得到响应......现在我希望它通过可观察模式收到通知我的视图
观察者似乎是一个构造函数,你用var o = new Observer();
调用它,然后o
将是一个引用一堆函数的对象。 您可以通过 subscribe
将函数添加到列表中。 并通过unsubscribe
将它们从列表中删除
那么这一切的全部意义在于" fire
"方法,它将遍历函数列表,然后逐个调用每个函数。 "observer pattern"
似乎很像单例模式
你熟悉JavaScript中的"watch
"方法吗?这是一种通过 Firefox 支持的方法,您可以在任何对象上使用。
document.myform.myfield.watch('value', function (v) {
alert(v);
return v;
})
然后,每当对象的值发生变化时,都会调用watch
函数。 所以基本上观察者模式背后的概念是,你想以跨浏览器的方式模拟 Firefox 的 watch 方法。
您将对一堆函数或对象的引用扔到订阅list.then
Observer.fire
对每个监视的对象或函数调用回调方法。这样,如果用户执行某种操作(例如单击),则整个函数列表将通过回调函数更新
我希望这有所帮助。
如果你只想做一个简单的请求,那么在jQuery中(例如使用$.ajax(...)
或$.get(...)
)将如下所示:
var requestUrl = "text.html";
// Callback is defined here
var viewCallback = function(data) {
// this will be called when the request is done
console.log('view is notified');
console.log('data looks like this:');
console.log(data);
// you could chain method calls to other callbacks here if you'd like
};
// Request is done here
$.ajax({
url: requestUrl,
}).done(viewCallback);
大多数情况下,在执行上述代码足够的请求时,您只想做一件事。使用jQuery或mootools等JavaScript库将抽象出XMLHttpRequest对象的奇怪之处。
但是,如果你想做一些更高级的事情,我建议你看看做这种事情的库,比如Radio.js。