admin管理员组

文章数量:1356908

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.

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

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.

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

Share Improve this question edited Apr 25, 2012 at 10:50 theJava asked Apr 25, 2012 at 10:44 theJavatheJava 15k48 gold badges134 silver badges174 bronze badges 4
  • 2 What don't you understand? en.wikipedia/wiki/Observer_pattern – Matt Commented Apr 25, 2012 at 10:46
  • @Matt: 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. – theJava Commented Apr 25, 2012 at 10:49
  • @theJava: You usually do this through callbacks. I.e. the function you send as an argument when you do the request e.g. in jQuery to the $.ajax(...). Usually there is no need to set up observers. But if you really do need the posability of observer pattern then there is a 3rd party library for this called Radio.js. – Spoike Commented Apr 25, 2012 at 11:00
  • You seem to have a solution (Observer Pattern) looking for a problem. That sounds like a homework request. Consider adding the "homework" tag and clarifying your assignment. If this is not homework, try stating what you are trying to achieve clearly and without assuming the Observer pattern is the right solution. – ddaa Commented Apr 25, 2012 at 11:19
Add a ment  | 

2 Answers 2

Reset to default 4

Observer appears to be a constructor that you call with var o = new Observer(); then o will 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

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

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

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

then whenever the value of the object changes, the watch function 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

you toss a reference to a bunch of functions or objects into subscribed list.then have Observer.fire call 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

I hope this helps.

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

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.

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

本文标签: Usage of Observable pattern in JavaScriptStack Overflow