Question

I have a close function that will close some instance. The class that includes the function allows derived classes to override close. Here, I want to make sure that close always calls dispose even in derived classes. I achieve this by the following.

function close() {
  closeCore();
  dispose();
}

function closeCore() {
  // derived class can override this method.
}

This works fine, but I have one case where I want to perform CSS animation before I dispose the instance. This is what I do.

function close () {
  instance.classList.add("fancy-animation-that-takes-800ms");

  setTimeout(function () {
    dispose();
  },800);
}

But as soon as I do this, the template pattern I use cannot be applied. Is there a way to make sure the close function always call dispose in the second example?

Was it helpful?

Solution

You might have close expect an object be returned from closeCore which had parameters like these:

return {timeout: 800, callback: function () {/*....will execute after a timeout..*/}};

or:

return {callback: function () { /*...will be immediately executed...*/}};

or:

return function () { /*...will be immediately executed...*/};

...and then call their timeout for them (if any), and then after your timeout executed their callback, then call dispose for them.

The relevant part of your close code might look like:

function close() {
  var ccObj = closeCore();
  var ccIsObj = ccObj && typeof ccObj === 'object';
  var callback = typeof ccObj === 'function' ? ccObj : (ccIsObj ? ccObj.callback : null);
  if (ccIsObj && ccObj.timeout) {
    if (!callback) {
      throw 'You must implement a callback when supplying a timeout';
    }
    setTimeout(function () {
        callback();
        dispose();
    }, ccObj.timeout);
  }
  else {
    if (callback) {callback();}
    dispose();
  }
}

But if you want to allow the user to make arbitrary asynchronous calls of their own (such as Ajax), while you could instead allow the returning of a promise to which you added the dispose call, you wouldn't have a guarantee that the deriver would ensure the promise completed. You could automatically cancel the promise after a certain period of time, but you couldn't magically know when the deriving code was meant to finish unless again you abstracted this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top