Observer Pattern using jQuery

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.
    1. (function($) {
    2. function Enemy(element, options) {
    3. this.init();
    4. }

    5. Enemy.prototype = {
    6. init : function() {
    7. console.log('ENEMY init');
    8. },

    9. run : function(event) {
    10. console.log('ENEMY run');
    11. console.log(event.data.obj);
    12. },

    13. attack : function(event) {
    14. console.log('ENEMY attack');
    15. console.log(event.data.obj);
    16. }
    17. };

    18. window.enemy = new Enemy();
    19. })(jQuery);

    1. (function($) {
    2. function Pacman() {
    3. this.init();
    4. }

    5. Pacman.prototype = {
    6. init : function() {
    7. console.log('PACMAN init');
    8. },

    9. eat : function() {
    10. console.log('PACMAN eat');
    11. $(this).eventDispatch('pacman.eat');
    12. }
    13. };

    14. window.pacman = new Pacman();
    15. })(jQuery);

    1. (function($) {
    2. var observers = [];

    3. $.fn.eventAdd = function(event, callback) {
    4. console.log('EVENT_ADD');

    5. //only add object if it exists
    6. if ($(this).length > 0)
    7. observers.push({
    8. event : event,
    9. callback : callback,
    10. obj : this
    11. });
    12. };

    13. $.fn.eventDispatch = function(event) {
    14. console.log('EVENT_DISPATCH');

    15. $.each(observers, function(key, observer) {
    16. //need to understand and refine this object
    17. var passEvent = {
    18. data : observer
    19. };

    20. if (event == observer.event)
    21. observer.callback(passEvent);
    22. });
    23. };
    24. })(jQuery);

    Use:
    1. (function($) {
    2. $(document).ready(function() {
    3. $('#enemy1').eventAdd('pacman.eat', enemy.run);
    4. $('#enemy2').eventAdd('pacman.eat', enemy.attack);

    5. pacman.eat();
    6. });
    7. })(jQuery);