Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of Observable pattern in JavaScript

Tags:

javascript

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

like image 206
theJava Avatar asked Apr 25 '12 10:04

theJava


1 Answers

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.

like image 104
Thalaivar Avatar answered Oct 29 '22 07:10

Thalaivar