« Buntel Bounces | ^ Main | Wildcard Cert Install »
C# & Flash Differences: Event Listener Assignments
Ok…me coming from Flash I was expecting some sort of method (or 3) in C# used for adding/removing event listeners and dispatching them. Well, I was terribly mistaken. :-)
While I was working on the Simple Calculator I decided to jump ahead in the dev process and peep some of the code Visual Studio was creating for me with the visual changes I was making. In doing so I found the InitializeComponent method which init’s all of the buttons, menus, etc.
Let’s peep some code.
// C# Code
// number5
//
this.number5.Location = new System.Drawing.Point(47, 131);
this.number5.Name = "number5";
this.number5.Size = new System.Drawing.Size(31, 31);
this.number5.TabIndex = 6;
this.number5.Text = "5";
this.number5.UseVisualStyleBackColor = true;
this.number5.Click += new System.EventHandler(this.numberButton_Click);
Ok. This seems normal. You have an object (a button) called number5. this is referring to the current object scope and you set several attributes for the object (location, name, size, etc). Uh oh, += on an event handler? What the heck is that?
Let’s first back track to what += means in dev terms (namely ECMA). += means take what is on the left side of the + sign and add it to itself and whatever is on the right side. This is used in Math operations a lot.
var a = 10;
a += 5;
//a now equals 15
So what is += doing with the event handler on the right side? Well, it is assigning the method this.numberButton_Click to the click event. This is 100% equivalent to the addEventListener in Actionscript.
//AS Code
this.number5.addEventListener("click", this.numberButton_Click);
See, the same thing. Obviously you want to know how to remove an event handler in C# don’t you? Well, I’m glad you asked.
this.number5.Click -= new System.EventHandler(this.numberButton_Click);
Once you think about it this actually makes since. You want the click event on the button to add an even to itself so you use += and -= for removing. This threw me for a second but I totally get it now.
Posted by John C. Bland II on February 14, 2006 12:12 AM | Permalink
TrackBack
TrackBack URL for this entry:
http://mt.katapultmedia.com/mt-tb.cgi/26



