See a lot of examples on the net, also turn many ebook! Inadvertently read this friend's notes let me have an epiphany! Hope to you also helpful!!!
Address: http://ju.outofmemory.cn/entry/106079
Understanding the Observer pattern
In a nutshell, an object is an observer of the activity of a particular task or another object, and when that task or activity occurs, the observer is notified by the form of an event.
the use of the viewer
You should consider using the observer pattern when an object's changes need to change other objects at the same time, and it does not know how many objects need to be changed.
For example, the user a,b,c to subscribe to a service, when the service has updates can be set updates, downloads and other operations.
Simulation Implementation
Defines the observable object, which contains 2 methods: Add (Subscribe) and Fire (publish) method
Observer var Observable = { callbacks: [], add:function (FN) { this.callbacks.push (FN); }, Fire : function () { This.callbacks.forEach (function (FN) { fn (); })} } Subscription Observable.add (function () { console.log (1);}) Observable.add (function () { console.log (2);}) Release Observable.fire (); 1, 2
Practical Application
In real business, such as requesting an AJAX, you need to execute multiple methods, data processing, rendering pages, other business, etc., you can use the Observer
Observable.add (function () { //pocessdata}) Observable.add (function () { $ (' test '). HTML (DATA.A) $ ( ' Test2 '). HTML (DATA.B) $ (' test3 '). html (DATA.C)}) Observable.add (function () { //pocessother}) $. Ajax ({ URL: "test.html", context:document.body}). Done (function (data) { observable.fire (data)})
I'll be writing when I'm not looking at the pattern.
$.ajax ({ URL: "test.html", context:document.body}). Done (function (data) { $ (' test '). HTML (DATA.A); $ (' test2 '). HTML (data.b); $ (' test3 '). HTML (DATA.C); })
Look, feel no problem exists! Completely realized the same function!!
At this point, the project needs to add another feature on this basis! If it is a function of ' system recommend product '! Then how to change it? yes, my de is written on the basis of the original code! no problem??
Although the functionality is also implemented, if the feature requires replacement! What to do, is not to go to find the previous code to remove the rewrite, and also to check if there were any other reference pointers! How to change this, it is better to delete all the rewrite, come happy.
But using the observer mode, to solve this problem, by the way you add, how to modify, I have a notification OK, do not have to worry about breaking the previous code or colleague's code!
Design mode I've just touched this stuff! There's nothing wrong with de place! Please correct me! Thank you!
JavaScript Design Patterns-observer patterns