javascript create class event - Stack Overflow

How do I create a custom event for a javascript class? Example Codefunction somefunction(url){this.h_w

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

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);
}
Share Improve this question asked Mar 12, 2012 at 15:54 Kevin PeiKevin Pei 5,8727 gold badges40 silver badges55 bronze badges 1
  • No events are generated by the simple execution of JavaScript code (outside of some special behavior in Firefox around property "watch" settings). – Pointy Commented Mar 12, 2012 at 15:59
Add a ment  | 

2 Answers 2

Reset to default 5

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/remibreton/xzeEd/

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744874648a4598474.html

相关推荐

  • javascript create class event - Stack Overflow

    How do I create a custom event for a javascript class? Example Codefunction somefunction(url){this.h_w

    1天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信