Skip to content

Instantly share code, notes, and snippets.

@gauravv7
Last active August 15, 2018 11:53
Show Gist options
  • Select an option

  • Save gauravv7/a994fb05dbee9ccc828423f605654327 to your computer and use it in GitHub Desktop.

Select an option

Save gauravv7/a994fb05dbee9ccc828423f605654327 to your computer and use it in GitHub Desktop.
/**
* issue #52(hot fix)
* the below code is to replace the DomNodeInserted JQuery block code(django-easy-selectv1.5.3/easy-select2.js) with below implementation as it is.
* this implementation is confirmed for issue-52
* (currently in performance testing to make a production release for this implementation)
*/
// Select the node that will be observed for mutations
var targetNode = document.documentElement || document.body;
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
console.log(mutation);
if(mutation.addedNodes.length){
$.each(mutation.addedNodes, function(idx, val){
var targetClassNames = $(val).attr('class'); // new tr added
if(targetClassNames===undefined
||
(targetClassNames.indexOf('form-row')==-1 && targetClassNames.indexOf('dynamic-')==-1)
) return;
var $select2Eles = $(mutation.target).find('div.field-easy-select2:not([id*="__prefix__"])');
if($select2Eles.length) {
$(mutation.target).find('div.field-easy-select2:not([id*="__prefix__"])').each(function () {
// taking data-* for select2 constructor properties for backward compatibility
var obj = $(this).data();
// merging the options and data properties, modifying the first
// NOTE: obj properties will be overwritten by options
// https://api.jquery.com/jquery.extend/
$.extend(obj, options);
redisplay_select2($(this), obj);
});
} else {
$.each(_all_easy_select2_ids, function(idx, val){
var obj = $("#" + val).data();
$.extend(obj, options);
$("#" + val).select2('destroy').select2();
});
}
})
}
}
else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment