我知道這可能是一個遠景,但我想看看這是否可行 - 我在我創建的物件中有以下方法:
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']
});
}
現在我在另一個檔案中有完全相同的代碼邏輯,即:
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();
});
它們之間的唯一區別是里面的內部專案if (mutation.attributeName === 'src')。
問題:
是否可以重用我的物件函式,src_observer()但在它們之間傳遞各種函式和元素if (mutation.attributeName === 'src'),這樣我就可以重用該方法并將其他函式和元素傳遞給其他地方。
實際上,看看這樣的事情:
src_observer(target_node, { target_show_element, target_next_element, pass_in_additional_elements }- 所有幫助將不勝感激!
uj5u.com熱心網友回復:
當然,只需傳入一個回呼:
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']
});
}
那么第一次使用將是:
src_observer(target_node, () => {
target_node.show();
target_node.next().remove();
});
第二個類似于(這里更難確定,因為代碼的兩個參考位涵蓋了不同的領域):
src_observer(target_node, () => {
videoWrapper.parents().eq(1).children('.onetrust_container').remove();
videoWrapper.parent().show();
videoWrapper.show();
element.fadeOut(500);
cover.fadeOut(500);
});
(您甚至可以通過指定確定給定突變記錄是否與條件匹配的“測驗”回呼來對其進行更多引數化。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/359914.html
標籤:javascript 查询
