本文介绍了我可以在Javascript中为我创建的对象创建自定义事件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个成员函数返回自身的对象:
Assume I have an object with a member function that returns itself:
/* -- Object 1 -- */
function Object1(){
this.me = new Image(10,10);
this.me.src = "someImgUrl.jpg";
this.publish = function(){
return this.me;
}
}
生产中:
var Obj1 = new Object1();
document.body.appendChild( Obj1.publish() );
现在,假设我想创建一个在调用对象的publish()方法时触发的事件,但是在返回图像之后(类似于onPublished()事件)。比如说,要将图像尺寸更改为100x100。我将如何创建它,以及在哪里附加它?
Now, suppose I wanted to create an event that fires when the object's publish() method is called, but after the image is returned (something akin to an "onPublished()" event). Say, to to change the image dimensions to 100x100. How would I create it, and where would I "attach" it?
如果我不够清楚,请告诉我。这是我能想到的最简单的演示。
If I'm not being clear enough, please let me know. This is the simplest demo I could think of.
推荐答案
一个简单的例子:
function Object1() {
'use strict';
this.me = new Image(10, 10);
this.me.src = "someImgUrl.jpg";
this.publish = function() {
if (typeof this.onPublish === "function") {
setTimeout(this.onPublish, 1);
}
return this.me;
};
}
var Obj1 = new Object1();
Obj1.onPublish = function() {
// do stuff
};
Obj1.publish();
这篇关于我可以在Javascript中为我创建的对象创建自定义事件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!