Removing DevExtreme widgets from the DOM

Oliver's Blog
01 November 2016

I was working on a few samples recently and stumbled upon this problem: when a widget created by our DevExtreme library was removed from the DOM, it wouldn't re-render itself on the same node later on.

Initially I was using code like this to remove child nodes from the target node:

while (node.lastChild) {
  node.removeChild(node.lastChild);
}​

This didn't work and after a bit of debugging, I tried to also reset node attributes that might have been added, in order to restore the target node to its original state:

$.map(node.attributes, a => a.name).
  forEach(n => {
    if (n != "id") {
      node.removeAttribute(n)
    }
  });

However, I was still unable to render a new widget in the same node later on. So the research continued, and with the help of our team I figured out that additional information is stored using the jQuery data() helper, and this also needs to be cleaned up properly. It is a good recommendation to call the _dispose() function on the widget to make sure any internal clean-up is performed at this point. Overall I ended up with this helper function to clean up the target node completely:

function clearNode(node) {
  const chartData = $(node).data("dxChart");
  if (chartData) {
    chartData._dispose();
    $(node).removeData("dxChart");
  }
  const componentData = $(node).data("dxComponents");
  if (componentData) {
    $(node).removeData("dxComponents");
  }
  
  while (node.lastChild) {
    node.removeChild(node.lastChild);
  }

  $.map(node.attributes, a => a.name).
  forEach(n => {
    if (n != "id") {
      node.removeAttribute(n)
    }
  });
}

I have created a sample that shows the use of this code:

Finally, note that the widgets always store their data in this way, regardless of the library you use to instantiate them. In other words, if you use our Knockout or Angular support, the data is stilled stored using the jQuery mechanism, and you would need similar steps if you were to manually remove a widget from a node.

no comments
No Comments

Please login or register to post comments.