While patching Views I added this to an existing JS file thanks to caseyn. You can replace the iframe-related code (which is just two lines) to add your JS to Drupal:
// Magic incantation line 0 from comments
(function($, Drupal) {
// Magic incantation line 1. The Drupal.behaviors. is mandatory,
// the viewsUiPreview is arbitrary.
Drupal.behaviors.viewsUiPreview = {
// Magic incantation line 2.
attach: function (context, settings) {
// #preview-submit is a selector and context must be
// passed into jQuery so for an AJAX request only the
// new content is used.
$('#preview-submit', context).click(function() {
// This is the actual JS code. The var $iframe
// could be moved one line up for a minor speedup.
var $iframe = $('#preview-iframe');
$iframe.attr('src', $iframe.attr('src'));
})
}
}
})(jQuery, Drupal);
This is tied into Drupal with this code:
$form['#attached']['js'][] = drupal_get_path('module', 'views_ui') . '/js/views-admin.js';
Commenting on this Story is closed.
First, using the attached element on a form is important. This should be used rather than drupal_add_js() when using forms or renderable arrays because it works with Drupal caching better.
Second, in the JS code example you are creating and possibly clobbering a global variable named
$iframe
. Variables in JS are not scoped to the local block level when there is no var in front of them. In this case it's a global variable. A way to avoid that would be use something like:(function($, Drupal) {
// Magic incantation line 1. The Drupal.behaviors. is mandatory,
// the viewsUiPreview is arbitrary.
Drupal.behaviors.viewsUiPreview = {
// Magic incantation line 2.
attach: function (context, settings) {
// #preview-submit is a selector and context must be
// passed into jQuery so for an AJAX request only the
// new content is used.
$('#preview-submit', context).click(function() {
// This is the actual JS code.
var $iframe = $('#preview-iframe');
$iframe.attr('src', $iframe.attr('src'));
})
}
}
})(jQuery, Drupal);
This does 2 things:
var $iframe
line could be outside of the binding, to save parsing time in a second click.Not worthy if it's expected only 1 click per page though.
--
corbacho
One problem is that this kind of code might register two click handlers if the attach is executed twice on the same content, so use something like live() or check for some "foo-processed" class see drupal core examples.
$('#preview-submit', context).live('click', function() {
});