Sé que esto es probablemente una posibilidad remota, pero quería ver si esto es posible. Tengo el siguiente método dentro de mi objeto que creé:
function src_observer(target_node) { let observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if (mutation.attributeName === 'src') { target_node.show(); target_node.next().remove(); } }); observer.disconnect(); }); // Pass in the Observer target node & options observer.observe(target_node[0], { attributes: true, attributeFilter: ['src'] }); }
Ahora tengo exactamente la misma lógica de código en otro archivo, que es:
let target_node = videoWrapper.html(videoElement).children('iframe')[0]; // Set our Observer options let config = { attributes: true, attributeFilter: ['src'] } // Observe and listen for the src data attribute let src_observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if (mutation.attributeName === 'src') { videoWrapper.parents().eq(1).children('.onetrust_container').remove(); videoWrapper.parent().show(); videoWrapper.show(); element.fadeOut(500); cover.fadeOut(500); } }); src_observer.disconnect(); });
La única diferencia entre ellos son los elementos internos dentro de if (mutation.attributeName === 'src')
.
Pregunta :
¿Es posible reutilizar la función de mis objetos src_observer()
pero pasar varias funciones y elementos intermedios if (mutation.attributeName === 'src')
para que pueda reutilizar ese método y pasarle otras funciones y elementos en otro lugar?
Siendo realistas, mirando algo como esto:
src_observer(target_node, { target_show_element, target_next_element, pass_in_additional_elements }
- ¡Toda ayuda será apreciada!
Claro, solo pasa una devolución de llamada:
function src_observer(target_node, callback) { let observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if (mutation.attributeName === 'src') { // This call to `disconnect` seemed like it should be // here rather than outside this block observer.disconnect(); // Call the callback to do the specific work that // should be done when the mutation is seen callback(mutation); } }); }); // Pass in the Observer target node & options observer.observe(target_node[0], { attributes: true, attributeFilter: ['src'] }); }
Entonces el primer uso sería:
src_observer(target_node, () => { target_node.show(); target_node.next().remove(); });
Y el segundo sería algo así como (es más difícil estar seguro aquí, porque los dos bits de código citados cubren un terreno diferente):
src_observer(target_node, () => { videoWrapper.parents().eq(1).children('.onetrust_container').remove(); videoWrapper.parent().show(); videoWrapper.show(); element.fadeOut(500); cover.fadeOut(500); });
(Incluso podría parametrizarlo más especificando una devolución de llamada de "prueba" que determina si un registro de mutación dado coincide con la condición).