var pixelCount = 12;
$('.container').on("click", function moveLeft(event, pixelCount)) {
var newPixelCount = 100 + pixelCount;
});
My problem is that I can’t pass in pixelCount - it is undefined within the jquery callback. I know that if I remove pixelCount from the callback’s arguments, it works, because it can access the global scope and finds var pixelCount there. But I want to be able to pass an argument INTO the callback and not rely on the global scope. I also want to preserve access to the event variable.
Is there a way to do this? If there isn’t, what is the best way to handle this without potentially abusing global scope?
I don’t think there’s an immediate way to do this… jQuery events are actually wrappers around native DOM events (which you can access via event.originalEvent). So what you might do is re-dispatch the click as a a custom event with the pixel count set on the detail property:
function addCustomListener(element, namespace, type, data) {
element.addEventListener(type, function (event) {
var newEvent = new CustomEvent(namespace + ':' + type, {
detail: {
data: data,
originalEvent: event
}
})
element.dispatchEvent(newEvent)
})
}
var container = document.getElementById('container')
container.addEventListener('my:click', function (event) {
var pixelCount = 100 + event.detail.data
// ...
})
addCustomListener(container, 'my', 'click', 12)
I’m not entirely sure if this makes things much cleaner though. :-)