Experimenting with bind
, call
, and apply
, I am exploring updating object properties by passing function return values to object methods.
This updating is triggered by the window
resize event.
var el = document.getElementById('someElement');
var resolveLeft = function(element) {
return element.offsetLeft;
};
var someObject = {
setDefaultLeft: function(value) {
this.defaultLeft = value;
console.log(this.defaultLeft);
}
};
// works fine
window.addEventListener('resize', function() {
someObject.setDefaultLeft(resolveLeft(el));
});
// doesn't work as expected
window.addEventListener('resize', someObject.setDefaultLeft.bind(someObject, resolveLeft(el)));
#someElement {
position: absolute;
left: 10%;
}
<div id="someElement"></div>
I have two event bindings. The first logs an updated value every window resize, while the second only logs the initial returned value.
In the second case, the value was already returned from resolveLeft
and does not revisit the function on subsequent calls. It simply reuses the initial return value.
Is there a workaround for this issue?
I believe currying might offer a solution, but unsure how to implement it in this scenario.