Whenever I come across repetitive blocks of code in my program, it always makes me think that there must be a more efficient way to design it.
As an example, let's consider the following snippet:
const obj = new SomeAjaxObject();
obj.on('load', () => {
doSomething(obj); //obj needs to be loaded for this to work
})
The issue here is that if obj
is already loaded when I bind the load
event, the doSomething
function will never be triggered.
My workaround for this problem was as follows:
const obj = new SomeAjaxObject();
if(!obj.loaded){ //This property is synchronous
obj.on('load', () => {
doSomething(obj);
})
}else{
doSomething(obj);
}
Is there a more elegant solution to achieve the same result without having redundant code?
Keep in mind that I have no ability to modify the source code of SomeAjaxObject
.