Im tring to use the observer pattern in javascript with JQuery, but the trigger and bind doesnt work. How may i do it to get the “alert(‘notify binded’);” run? 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);
Here are few remarks about your code:
notificationsarray is always empty –[]. There’s nothing in your code which puts elements inside it so the bind function binds to nothing.NoteApp = new NoteApp();should be called when the DOM is ready or theask_number,ask_emailandask_outelements might not yet be initialized.