Skip to content

Reattaching after a DOM update

digitalhurricane edited this page Dec 4, 2014 · 4 revisions

When you inject HTML (eg. AJAX) the HTML can contain data-attach attributes. To attach JavaScript to this newly injected HTML you'll need to call Attach.run(). A nice way of of doing this is by triggering an event after updating.

You can use this technique in combination with storing instance references to avoid attaching things twice.

###jQuery

//Inject some stuff then..
$(document).trigger('updated');
$(document).on({
  'ready': function () {
    Attach.run();
  },
  'updated': function () {
    Attach.run();
  }
});

###MooTools

//Inject some stuff then..
window.fireEvent('domupdated');
window.addEvents({
  'domready': function () {
    Attach.run();
  },
  'domupdated': function () {
    Attach.run();
  }
});