需要能够任意创建事件(甚至是在运行时创建的事件),然后将此类事件的事件监听器任意绑定(bind)到元素。
在下面的代码中,一切都完全按照计划进行,除了 XBS.pullCurtain()
从未被调用(但事件会触发!)。我已经检查并重新检查了参数、顺序等,没有抛出任何错误,一切似乎都是我所期望的。但事件监听器没有任何酱料。 :S
// this func is used in the larger object below
function eCustom(eName, eProperties) {
var defaultProps = {"bubbles":true, "cancelable":false, "eventPhase":0, "type":eName};
if (typeof(eProperties) == "object") {
for (var prop in eProperties) {
if (eProperties.hasOwnProperty(prop) ) {
defaultProps[prop] = eProperties[prop];
}
}
}
return jQuery.Event(eName, defaultProps);
}
window.XBS = {
cfg: {
minLoadTime: 1000
},
evnt: {
wakeFromSleep: eCustom("wakeFromSleep"),
assetsLoaded: eCustom("assetsLoaded")
},
init: {
// obviously will be expanded haha
XBS.initImages();
},
stopwatch: {
__sw: new Date(),
reset:function() { XBS.stopwatch.startTime = -1},
start: function() {
var now = XBS.stopwatch.__sw.getTime();
XBS.stopwatch.startTime = now;
return now;
},
read: function() { return XBS.stopwatch.__sw.getTime() - XBS.stopwatch.start;},
now: function() { return XBS.stopwatch.__sw.getTime();},
elapsed: function(period) {
var diff = XBS.stopwatch.now() - XBS.stopwatch.startTime;
return (period !== undefined) ? diff > period : diff;
},
startTime:-1
},
sleep: function(period, wakeEvent, onWake, target) {
if (wakeEvent == undefined) wakeEvent = XBS.evnt.wakeFromSleep;
if (isFunction(onWake) ) {
// confirmed code reaches these lines and all vars are as expected
if (target == undefined) target = window;
$(target).on(wakeEvent, onWake);
}
setTimeout(function() {$(target).trigger(wakeEvent) }, period);
},
initImages: function() {
XBS.stopwatch.start();
// loadImages is a jQuery extension (link at bottom), but it works like a charm—
// problem isn't there, I'm 99% sure
$("#image-loading-queue").loadImages({
allLoadedClb:function() {
var success = null;
//minLoadTime because there will be presentational animations
if (XBS.stopwatch.elapsed(XBS.cfg.minLoadTime)) {
success = true;
} else {
var elapsed = XBS.cfg.minLoadTime - XBS.stopwatch.elapsed();
XBS.sleep(elapsed, XBS.evnt.wakeFromSleep, XBS.pullCurtain, "#curtain");
}
}
});
// this return is a placeholder for pending functionality, which is why it's not used
return success;
},
pullCurtain: function() {
// this will get more elaborate, but for now, I just want to call the darn thing!
$("#curtain").fadeToggle();
}
}
借阅的图书馆: http://www.jqueryscript.net/loading/Asynchronous-Image-Loading-with-jQuery-Image-Loader-Plugin.html
最佳答案
您的 jQuery 中有错误 on
方法调用(您的 JavaScript 控制台可能会提示)。 on
的第一个参数应该只是要处理的事件的名称(字符串),而不是 jQuery Event 对象。查看文档。它有两个签名:一个采用方法名称(例如 'click'
),另一个采用多个方法名称到函数的映射(例如 {'click': fn1, 'mouseover ':fn2}
)。它没有 jQuery Event 对象的方法签名。
绑定(bind)处理程序时,更改行以仅传递事件名称:
$(target).on(wakeEvent.type, onWake);
关于javascript - jQuery:具有动态绑定(bind)、任意创建的事件和监听器的事件序列未完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25880666/