在JavaScript中创建事件,比如c#
本文关键字:比如 事件 创建 JavaScript | 更新日期: 2023-09-27 18:13:41
我主要用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中做等效的?谢谢你!
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();
你可以像这样在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>
使用javascript自定义事件
自定义Javascript事件
如果你喜欢使用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
}
}