What is more performant way to assign events?
Not taking code quality into account since it is sort of opinion-based thing.
Delegated binding + data attributes
var o = [{ key: "1", value: "one" }, { key: "2", value: "two" }, { key: "3", value: "three" }];
var $container = $("#container");
$.each(o, function() {
$("<button/>").text(this.key).data("value", this.value).appendTo($container);
});
$(document).on("click", "button", function() {
console.log($(this).data("value"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
Single direct bindings + closured value
var o = [{ key: "1", value: "one" }, { key: "2", value: "two" }, { key: "3", value: "three" }];
var $container = $("#container");
$.each(o, function() {
var x = this;
$("<button/>")
.text(x.key)
.click(function() {
console.log(x.value);
})
.appendTo($container);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
If we use the first approach, then we win some performance because of the delegated event handler, but lose some because we are creating a jQuery object and reading data attributes.
Will the second approach take up more memory?