rails/pjax_rails — pull request #73 by monkbroc (2014-12-15 21:53:27+00:00)
Title: Adding beforeCache event to cleanup DOM

I'd like to discuss adding a pjax:beforeCache event that would allow the Javascript application to cleanup the DOM before it is cached by pjax during a click on a link.

I found that it was hard to reenable HTML widgets like jQuery calendars and Backbone views after a pjax popstate because all the jQuery event handlers were gone, but the DOM still contained all the tags for those widgets. So the widget would not work but could not be recreated from scratch either.

To solve this, I clone the original DOM container for the widget on page load, then before pjax caches the DOM I replace the "widgetized" DOM element by the original. When I navigate backwards and forward through the browser history, the widget gets recreated properly.

Here's an example:

```javascript
$(document).on('ready pjax:end', function() {
$('input.datepicker').each(function() {
var $this = $(this);
// Save original DOM element
var $original = $this.clone();

// Create datepicker widget on HTML input tag
$this.calendar();

// Cleanup datepicker
$(document).one('pjax:beforeCache', function() {
// Copy current value of HTML input tag
$original.val($this.val());

// Replace complex DOM element with the original simple one
$this.replaceWith($original);
});
});
});
```

Any thoughts? How have others dealt with reenabling HTML widgets on popstate?