我试图弄清楚从对象文字中绑定事件处理程序的最佳方法是什么。
想象以下对象:
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();
}
}
};
这里的问题是该方法可以从其他对象多次调用,这也将有效地多次调用addTopWarning
and并创建对相同对象的重复绑定。我知道我可以将它转换为实例对象,该对象在创建对象实例时初始化所有绑定,但同样 - 对于同一对象的多个实例,绑定也会发生多次。addTopConfirmation
topClose
topExecute
我更愿意将它保留为对象文字,因为这个特定对象比需要实例化的对象更像是一个帮助器。
我不知道如何处理它,所以如果有人可以提供建议 - 将不胜感激。