我有一些事件,我想作为一个委托绑定到文档对象,像这样:
$(document).on('click', '.create-post', Fti.Modals.createPostModal.open);
$(document).on('click', '.flag', Fti.modalHelper.openFlagModal);
$(document).on('click', '.login', Fti.Modals.loginModal.open);
$(document).on('click', '.register', Fti.Modals.registerModal.open);
通过一些创造性的重构,我这样做了:
选项1。
var eventTriggers = [
{
element: '.create-post',
event: Fti.Modals.createPostModal.open
},{
element: '.flag',
event: Fti.modalHelper.openFlagModal
},{
element: '.login',
event: Fti.Modals.loginModal.open
},{
element: '.register',
event: Fti.Modals.registerModal.open
}
];
for(var i = i, len = eventTriggers.length; i < len; i++){
$(document).on('click', eventTriggers[i].element, eventTriggers[i].event)
}
我想知道是否只是将一个事件绑定到文档对象并根据事件目标执行切换情况会更好,像这样:
选项2。
var eventTriggers = [
{
element: '.create-post',
event: Fti.Modals.createPostModal.open
},{
element: '.flag',
event: Fti.modalHelper.openFlagModal
},{
element: '.login',
event: Fti.Modals.loginModal.open
},{
element: '.register',
event: Fti.Modals.registerModal.open
}
];
var elements = eventTriggers.map(function(item){
return item.element;
});
$(document).on('click', elements.join(','), function(e){
var $target = $(e.target)
for(var i = 0, len = eventTriggers.length; i < len; i++){
if($target.hasClass(eventTriggers[i].element.substr(1))){
eventTriggers[i].event.call(e.target);
}
}
});
谁有任何建议或经验,哪个选项会表现更好?
使用多个侦听器以提高灵活性。如果您需要分离/删除一个,它不会影响其他的。
性能差异似乎可以忽略不计,大约10%取决于您的浏览器。在webkit浏览器中,添加单个事件侦听器似乎花费不到一毫秒(您的四个事件有时需要花费1ms来附加)。在i5 CPU上以100k次迭代运行此操作大约需要5到7秒。
除非你一直附加很多这样的事件,否则这似乎是一个过早优化的情况。如果可能的话,请考虑使用其他ID
选择器而不是class
选择器,因为这可能会节省更多的时间。
<a class="create-post">c</a><a class="flag">f</a><a class="login">l</a><a class="register">r</a>
<script>
$(document).ready(function () {
var iterations = 100000;
var simple = 0;
var trigger = 0;
var eventTriggers = [{
element: '.create-post',
event: function () {}
}, {
element: '.flag',
event: function () {}
}, {
element: '.login',
event: function () {}
}, {
element: '.register',
event: function () {}
}];
var mt = (new Date).getTime();
var iteration = 0;
while (iteration < iterations) {
$(document).on('click', '.create-post', function () {});
$(document).on('click', '.flag', function () {});
$(document).on('click', '.login', function () {});
$(document).on('click', '.register', function () {});
iteration++;
}
simple = (new Date).getTime() - mt;
var mt = (new Date).getTime();
var iteration = 0;
while (iteration < iterations) {
for (var i = 0; i < eventTriggers.length; i++) {
$(document).on('click', eventTriggers[i].element, eventTriggers[i].event);
}
iteration++;
}
trigger = (new Date).getTime() - mt;
console.log('simple: ' + simple + 'ms');
console.log('trigger: ' + trigger + 'ms');
console.log('diff: ' + (simple - trigger) + 'ms at ' + iterations + ' iterations');
});
</script>