Observer Pattern using jQuery
I got asked a while back in a test to implement the Observer Pattern using Javascript / jQuery. I did not understand the Pattern at that point and its taken me a while to get something running. I have no theory background so I had never heard of the Pattern plus I had to understand the difference between Observer and Publish/Subscribe (still slightly confused tho).
Does the code below seem to form a solid basis for the Observer Pattern? I tried to follow the idea of how Flash AS3 implements the pattern (or at least to my understanding).
Note: Ive sectioned the different code snippets for my own use as I would like to develop something reusable.
And yes I do realise this functionality already exists in jQuery but I had to write my own implementation in the test.
- (function($) {
- function Enemy(element, options) {
- this.init();
- }
- Enemy.prototype = {
- init : function() {
- console.log('ENEMY init');
- },
- run : function(event) {
- console.log('ENEMY run');
- console.log(event.data.obj);
- },
- attack : function(event) {
- console.log('ENEMY attack');
- console.log(event.data.obj);
- }
- };
- window.enemy = new Enemy();
- })(jQuery);
- (function($) {
- function Pacman() {
- this.init();
- }
- Pacman.prototype = {
- init : function() {
- console.log('PACMAN init');
- },
- eat : function() {
- console.log('PACMAN eat');
- $(this).eventDispatch('pacman.eat');
- }
- };
- window.pacman = new Pacman();
- })(jQuery);
- (function($) {
- var observers = [];
- $.fn.eventAdd = function(event, callback) {
- console.log('EVENT_ADD');
- //only add object if it exists
- if ($(this).length > 0)
- observers.push({
- event : event,
- callback : callback,
- obj : this
- });
- };
- $.fn.eventDispatch = function(event) {
- console.log('EVENT_DISPATCH');
- $.each(observers, function(key, observer) {
- //need to understand and refine this object
- var passEvent = {
- data : observer
- };
- if (event == observer.event)
- observer.callback(passEvent);
- });
- };
- })(jQuery);
Use:
- (function($) {
- $(document).ready(function() {
- $('#enemy1').eventAdd('pacman.eat', enemy.run);
- $('#enemy2').eventAdd('pacman.eat', enemy.attack);
- pacman.eat();
- });
- })(jQuery);