javascript创建类事件 [英] javascript create class event

查看:127
本文介绍了javascript创建类事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为JavaScript类创建自定义事件?

示例代码

How do I create a custom event for a javascript class?
Example Code

function somefunction(url){
   this.h_world = function(){/*some random code to do*/ };
}

var hw = new somefunction();

现在,对于一个非常简单的例子,如何创建一个自定义事件处理程序c $ c> hw.h_world 已完成执行并返回一些数据?

Now, for a very simple example, how do I create a custom event handler for this when hw.h_world has finished executing and return some data with it?

例如 p>

For example

var hw = new somefunction();
hw.h_world();
hw.finished_h_world = function(somedata){
  alert(somedata);
}


推荐答案

到h_world函数,并在完成后执行它

you can pass a callback function to h_world function and execute it on finish of it

function somefunction(url){
   this.h_world = function(cb){
      //do some operation
      if (cb && typeof cb === 'function') {
         cb();
         //cb.call(this, args1, arg2...); //execute callback in scope of current object
      }
   };
}

或者您可以像这样向您的类添加一个函数

or you can add a function to your class like this

function somefunction(url){
   this.h_world = function(){
      //do operation
      this.h_world_finish(parameters);   
   };
   this.h_world_finish = function () {};
}

var obj = new someFunction(url);
obj.h_world_finish = function (arg) {
    alert("finished h_world");
};
obj.h_world();

这篇关于javascript创建类事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆