JavaScript 中 Observable 模式的使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10314056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:25:47  来源:igfitidea点击:

Usage of Observable pattern in JavaScript

javascript

提问by theJava

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);

I am not able to understand the whole concept behind this. I want to implement this pattern in my project. I have a view where the form gets submitted and it calls an WebService and returns me response.

我无法理解这背后的整个概念。我想在我的项目中实现这种模式。我有一个视图,表单被提交,它调用一个 WebService 并返回响应。

If i have to implement this in my project where this a simple request and response... how would i go about with it? i understand you notify your observer when there is a change... let's take i make a request to my API and i get the response back... now i want it to get notified to my view back through observable pattern

如果我必须在我的项目中实现这个,这是一个简单的请求和响应......我将如何处理它?我知道你在发生变化时通知你的观察者......让我们向我的 API 发出请求,然后我得到响应......现在我希望它通过可观察模式得到通知给我的视图

采纳答案by Thalaivar

Observer appears to be a constructor that you call with var o = new Observer();then owill be an object with a reference to a bunch of functions. you add functions to the list via subscribe. and remove them from the list via unsubscribe

Observer 似乎是您调用的构造函数,var o = new Observer();然后o将是一个引用一堆函数的对象。您可以通过 将函数添加到列表中subscribe。并通过以下方式将它们从列表中删除unsubscribe

then the whole point of it all is the "fire" method which will loop through the function list then call each of the functions one by one . "observer pattern"appears to be a lot like the singleton pattern

那么这一切的重点是“ fire”方法,它将循环遍历函数列表,然后一个一个地调用每个函数。"observer pattern"看起来很像单例模式

Are you familiar with the "watch" method in JavaScript? its a method supported via Firefox that you can use on any object.

你熟悉watchJavaScript 中的 " " 方法吗?它是一种通过 Firefox 支持的方法,您可以在任何对象上使用它。

document.myform.myfield.watch('value', function (v) {
    alert(v);
    return v;
})

then whenever the value of the object changes, the watchfunction is called. so basically the concept behind the observer pattern is that you want to basically simulate Firefox's watch method in a cross-browser fashion

然后每当对象的值发生变化时,watch就会调用该函数。所以基本上观察者模式背后的概念是你想以跨浏览器的方式基本上模拟 Firefox 的 watch 方法

you toss a reference to a bunch of functions or objects into subscribed list.thenhave Observer.firecall a callback method on each of the watched objects or functions. that way if the user preforms some sort of action such as clicking, then the whole list of functions would be updated via a callback function

你把对一堆函数或对象的引用扔到订阅中,list.thenObserver.fire在每个被监视的对象或函数上调用一个回调方法。这样,如果用户执行某种操作,例如单击,则整个函数列表将通过回调函数更新

I hope this helps.

我希望这有帮助。

回答by Spoike

If you only want to do a simple request then in jQuery (such as with $.ajax(...)or $.get(...)) that would look like this:

如果你只想做一个简单的请求,那么在 jQuery 中(例如 with$.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);

Most of the time you only want to do one thing when doing a request for which the above is enough code. Using javascript libraries such as jQuery or mootools will abstract away the oddities with the XMLHttpRequest object.

大多数情况下,在执行上述代码足够的请求时,您只想做一件事。使用 jQuery 或 mootools 等 javascript 库将抽象出 XMLHttpRequest 对象的奇怪之处。

However if you want to do something much more advanced I'd recommend you look at libraries that do this sort of thing such as Radio.js.

但是,如果您想做更高级的事情,我建议您查看执行此类操作的库,例如Radio.js