I'm trying to figure out what's the best way to bind event handlers from within object literal.
Imagine the following object:
MySystem.ValidationTop = {
topClose : function() {
"use strict";
$(document).on('click', '#topCloseTrigger', function(event) {
// some action goes here
});
},
topExecute : function() {
"use strict";
$(document).on('click', '#topExecuteTrigger', function(event) {
// some action goes here
});
},
topWarningTemplate : function(thisWarning) {
"use strict";
// warning is wrapped and styled here
},
addTopWarning : function(thisWarning) {
"use strict";
if (typeof thisWarning !== 'undefined') {
this.addTop($(this.topWarningTemplate(thisWarning)));
this.topClose();
}
},
topConfirmationTemplate : function(thisConfirmation) {
"use strict";
// confirmation is wrapped and styled here
},
addTopConfirmation : function(thisConfirmation) {
"use strict";
if (typeof thisConfirmation !== 'undefined') {
this.addTop($(this.topConfirmationTemplate(thisConfirmation)));
this.topClose();
}
}
};
The problem here is that the method addTopWarning
and addTopConfirmation
can be called multiple times from other objects and this will effectively also call the topClose
and topExecute
multiple times and create duplicate bindings to the same objects. I know I could convert it to the instance object, which initialises all of the bindings when the instance of the object is created, but again - with multiple instances of the same object the bindings will occur several times as well.
I'd prefer to keep it as object literal as this specific object serves more as a helper than object that needs to be instantiated.
I can't figure out how to approach it so if someone could advice please - it would be very much appreciated.