像C#一样在JavaScript中创建事件

时间:2011-11-06 14:01:12

标签: c# javascript

我主要用C#编写代码。但是,我正在使用一些JavaScript。我在JavaScript中定义了一个类,如下所示:

function Item(id, name) {
    this.ID = id;
    this.Name = name;

    // define event submitCompleted
    this.submit = function() {
      // When the submission is completed, fire "submitCompleted" event.
    };
}

我的挑战是,我不知道如何在JavaScript中创建和触发自定义事件。如果这是C#,我会做以下事情:

public class Item
{
  public string ID { get; set; }
  public string Name { get; set; }

  public Item(string id, string name)
  {
    this.ID = id;
    this.Name = name;
  }

  public event EventHandler SubmitCompleted;
  public void Submit() 
  {
    // Submission logic
    SubmitCompleted(this, EventArgs.Empty);
  }
}

如何在JavaScript中执行等效操作?谢谢!

4 个答案:

答案 0 :(得分:3)

function Item(id, name, submitCompleted) {
    this.ID = id;
    this.Name = name;
    this.submitCompleted = submitCompleted;

    // define event submitCompleted
    this.submit = function() {
        // When the submission is completed, fire "submitCompleted" event.
        // we are passing 2 arguments to the callback: id and name
        submitCompleted(id, name);
    };
}

var item = new Item(1, 'some name', function(id, name) {
    alert('id = ' + id + ', name = ' + name);
});
item.submit();

答案 1 :(得分:0)

你可以在这样的javascript中创建自定义事件.....

<script type="text/javascript">
function Event()
{
     this.eventHandlers = new Array();
}

Event.prototype.addHandler = function(eventHandler){
this.eventHandlers.push(eventHandler);
}

Event.prototype.execute = function(args){

  for(var i = 0; i < this.eventHandlers.length; i++)
  {
     this.eventHandlers[i](args);
   }
}

function showName()
{
     alert("My name is stikiflem."); 
}

function getFaveMovie(arg)
{
     alert("My favourite movie is: " + arg + "."); 
}

function test()
{
     //create event
     myHandler = new Event();

    //add handler
    myHandler.addHandler(showName);
    myHandler.addHandler(getFaveMovie);

    //raise event
    myHandler.execute("Ghost in the Shell");
}

</script>
<body>
<input type="button" value="Click to create and execute events"
onClick="test()" />
</body>

答案 2 :(得分:0)

如果您更喜欢使用jQuery,那么非常简单

//to register an event
$(selector).bind('customEvent', eventHandler)

// to raise an event
$(selector).trigger('customEvent')

如果您正在寻找简单的JS方式,那么

var newObj = function(){
 var submitHdlr = [];
 this.bind = function(handler){
  submitHdlr.push(handler);
 }
 this.submit = function(){
  // do something
  for(i in submitHdlr) 
   i(); // raise each handler
 }
}

答案 3 :(得分:0)

在javascript中使用自定义事件定义

Custom Javascript Events