javascript create class event

2019-04-13 22:41发布

问题:

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();

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?

For example

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

回答1:

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();


回答2:

What you need is a callback function:

function somefunction(url){
   this.h_world = function(callback){
      var somedata = 'some data';
      callback(somedata);
   };
}

And then:

var hw = new somefunction();
hw.h_world(function(somedata){
    alert(somedata); // Will alert 'some data';
});

Here is a jsfiddle: http://jsfiddle.net/remibreton/xzeEd/