我创建了一个加载一些图像的自定义 JavaScript 对象:
function myCustomObject(){
//constructor and properties
this.initializeImages(); //this function will initialize images and call every other function.
}
myCustomObject.prototype.initializeImages(){
//some preperation code here
imageObj = new Image();
imageObj.onload = function (){
//after doing some things here I will call all remaining functions
if (allImagesLoaded=true){
this.method1();
this.method2();
this.method3();
//I want here to dispatch a custom event
$.event.trigger({
type: 'finish',
customeEventProperty: value
}
}
}
}
在我的主代码中,我想创建两个不同的customObjects
,并希望它们每个都在完成时触发事件,但我想知道是哪一个触发了它们。
$(document).ready(function (){
var myCustomObject1, myCustomObject2;
myCustomObject1 = new myCustomObject();
myCustomObject2 = new myCustomObject();
//if i do this I can't know which of the two fired the event
$(document).on('finish', function);
//How can I set up my event so I can do this?
myCustomObject1.on('finish', function1);
myCustomObject2.on('finish', function2);
});
换句话说,我如何知道哪一个触发了我的自定义事件?
最佳答案
您的customObjects是javascript对象而不是jQuery对象,因此您不能使用.on()
。您也无法在它们上触发事件,因为它们不是 DOM 元素。但是有不同的方法可以实现您想要的效果。
第一种方法在文档上设置事件监听器,并在其回调内部您可以读取哪个对象已触发。您还可以设置一个全局计数器变量来为您的自定义对象提供唯一的编号。优点是您只有一个中央处理程序 对于所有结束事件。
var objCounter = 0;
function func1() {/* Do something when obj 1 has finished */}
function func2() {/* Do something when obj 2 has finished */}
function myCustomObject(){
this.number = ++objCounter;
this.initializeImages();
}
$(document).on('finish', function(event) {
console.log(event.sender);
console.log(event.imageObj);
// now for example you can do:
if (event.sender.number == 1) func1();
});
myCustomObject.prototype.initializeImages(){
/* .... */
var that = this, // this refers to the customObject
imageObj = new Image();
imageObj.onload = function (){
/* ... */
if (allImagesLoaded=true){
/* ... */
$.event.trigger({
type: 'finish',
sender: that,
imageObj: imageObj,
customeEventProperty: value
});
}
};
}
第二种简单方法将处理程序作为属性附加到 customObject:
function myCustomObject(callback){
if (typeof callback == 'function') this.finish = callback;
this.initializeImages();
}
myCustomObject.prototype.initializeImages(){
/* .... */
var that = this, // this refers to the customObject
imageObj = new Image();
imageObj.onload = function (){
/* ... */
if (allImagesLoaded=true){
/* ... */
if(that.finish) that.finish(); // execute finish if its there
}
};
}
// now you can create a customObject with integrated callback:
var myCustomObject1 = new myCustomObject( func1 );
关于javascript - 在自定义对象上分配自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26376406/