Adding/Firing custom event using JavaScript
Today I found out a very cool way for adding custom events and fire them for any Client side object. This can be done using ASP.NET Ajax very easily. (Thank you Igor).
In order to create these events and fire them we will use the Sys.EventHandlerList Class. This class Creates a dictionary of client events for a component, with event names as keys and the associated handlers as values. It’s main method we need are the addHandler and getHandler. Lets see a simple example which is pretty self explanatory.
This sample creates a Book and a Library “classes”. The Library class will have a Add and a GetBook method that will fire an event when ever they are called. Here is the Code: (And again it is pretty self explanatory)
11 <form id="form1" runat="server">
12 <asp:ScriptManager runat=server ID="SM">
13 </asp:ScriptManager>
14 <div>
15
16 </div>
17
18 <script>
19 function Enums() {
21 throw Error.notImplemented();
22 }
23
24 Enums.ActionType = { Add: "Add", Get: "Get" }
26
27
28 function Book(name) {
29 this.Name = name;
30 }
31
32 function Library() {
33 this.Books = [];
34 }
35
36 Library.prototype.Add = function(book) {
37 this.Books[this.Books.length] = book;
38
39 this.fireEvent(Enums.ActionType.Add, book);
40 }
41
42 Library.prototype.GetBook = function(bookName) {
43 var retval = null;
44 for (var x = 0; x < this.Books.length; x++) {
45 if (this.Books[x].Name == bookName) {
46 retval = this.Books[x];
47 }
48 }
49 this.fireEvent(Enums.ActionType.Get, retval);
50 return retval;
51 }
52
53 Library.prototype.addHandler = function(eventId, handler) {
54 if (!this._events) {
55 this._events = new Sys.EventHandlerList();
56 }
57 this._events.addHandler(eventId, handler);
58 }
59
60 Library.prototype.fireEvent = function(eventId, book) {
61 var events = this._events;
62 if (!events) {
63 return false;
64 }
65
66 var handler = events.getHandler(eventId);
67 if (handler) {
68 handler(book);
69 }
70 }
71
72 var lib = new Library();
73 lib.addHandler(Enums.ActionType.Add, BookAdded);
74 lib.addHandler(Enums.ActionType.Get, BookUpdated);
75
76
77 function BookAdded(book) {
78 alert("A book was added:" + book.Name);
79 }
80
81 function BookUpdated(book) {
82 alert("A book was updated:" + book.Name);
83 }
84
85 lib.Add(new Book("C# book"));
86 lib.Add(new Book("VB.NET book"));
87 lib.GetBook("C# book");
88
89
90 </script>
91 </form>
Enjoy.