JQuery, javascript and observer pattern

Im tring to use the observer pattern in javascript with jQuery, but trigger and binding don't work. How can I do this to get a "warning (" notify related "); running? Thanks;)

(function($){ var NoteApp = function(){ var self = this; this.notifications = []; this.EVENT = { NOTIFY: 'notify' }; this.button = { ask_number: $('#ask-number'), ask_email: $('#ask-mail'), ask_out: $('#ask-out') }; var Button = function(){ }; var Data = function(app){ $(app.notifications).bind(app.EVENT.NOTIFY, function(){ alert('notify binded'); }); }(this); var UI = function(app){ app.button.ask_number.bind(app.EVENT.NOTIFY, function(){ alert('notify 2'); }); app.button.ask_number.click(function(){ //alert(app.EVENT.NOTIFY); $(app.notifications).trigger(app.EVENT.NOTIFY); return false; }) }(this); } NoteApp = new NoteApp(); })(jQuery); 
+4
source share
1 answer

Here are some notes about your code:

  • The notifications array is always empty - [] . There is nothing in your code that puts elements into it, so the bind function is not associated with anything.
  • NoteApp = new NoteApp(); should be called when the DOM is ready or the elements ask_number , ask_email and ask_out may not yet be initialized.
+2
source

Source: https://habr.com/ru/post/1306117/


All Articles