mraid页面事件监听避免这样写
在工作中,用到了 mraid.js 库,其中封装了事件监听逻辑,代码如下:
var EventListeners = function (event) { this.event = event; this.count = 0; var listeners = {}; this.add = function (func) { var id = String(func); if (!listeners[id]) { listeners[id] = func; this.count++ } }; this.remove = function (func) { var id = String(func); if (listeners[id]) { listeners[id] = null; delete listeners[id]; this.count--; return true } else { return false } }; this.removeAll = function () { for (var id in listeners) { if (listeners.hasOwnProperty(id)) { this.remove(listeners[id]) } } }; this.broadcast = function (args) { for (var id in listeners) { if (listeners.hasOwnProperty(id)) { listeners[id].apply(mraid, args) } } }; this.toString = function () { var out = [event, ":"]; for (var id in listeners) { if (listeners.hasOwnProperty(id)) { out.push("|", id, "|") } } return out.join("") } };

其中事件监听回调增加逻辑,是根据回调函数转为 String 之后来存储和判断的,当我们这样写
// mraid 监听页面是否展示 function onSdkReady(fn) { if (mraid.isViewable()) { fn && fn(); } else { mraid.addEventListener('viewableChange', function videoViewableChange(viewable) { if (viewable) { mraid.removeEventListener('viewableChange', videoViewableChange); fn && fn(); } }); } } // mraid show 判断,执行对应方法 function mraidShow(fn) { "use strict"; if (typeof mraid !== 'undefined') { if (mraid.getState() === 'loading') { mraid.addEventListener('ready', function(){ fn && onSdkReady(fn); }); } else { fn && onSdkReady(fn); } } else { fn && fn(); } }
原本我们想要封装下 mraid viewableChange 事件监听的逻辑,执行不同的回调函数,但是实际我们使用了同一个回到函数,通过在同一份回调函数中传参不同的方法来实现,结果只能第一次事件监听生效,后续监听的方法无法生效。
开发中类似逻辑要格外注意,修改后如下:
function onSdkReady(fn) { if (mraid.isViewable()) { fn && fn(); } else { typeof fn === 'function' && mraid.addEventListener('viewableChange', fn); } }
这样需要在实际传入回调函数的时候 接受 viewable 参数,来做判断。

浙公网安备 33010602011771号