Without events, it is imposable for the user to interact with the program. So, for this comparison I am going to wire up a simple click event (_btnUpdateText_Click()) that changes the text on a label (_txtHelloText) with the value of an integer that counts clicks (_clickNo). The sample is mind numbly simple to make the differences as stark as possible. I am using the same names where possible in both C# and JavaScript. So here goes:
Javascript HTML
- Create a JavaScript Windows Store Blank App, I’m calling mine “simpleEventJS”
- Open up default.html and paste the following on top of the existing body tag:
<body> <h1>Simple Events</h1> <div id="_txtHelloText">Button is still Unclicked</div> <button id="_btnUpdateText">Click Me</button> </body>
- Open js/default.js
- Insert the following code just above the call to app.start();:
// Just for proofiness, I will keep track of clicks and display in the event var _clickNo = 0; function _btnUpdateText_Click() { "use strict"; var control = document.getElementById("_txtHelloText"); control.innerText = "Click #" + (++_clickNo); }
- Replace args.setPromise(WinJS.UI.processAll()); with the following code:
args.setPromise(WinJS.UI.processAll().done(function () { var button1 = document.getElementById("_btnUpdateText"); button1.addEventListener("click", _btnUpdateText_Click, false); }) );
NOTE: On wiring the event, my first instinct would to wire it in the markup (onclick="_btnUpdateText_Click"). Experts recommend that you don’t do that, besides, if you put the event handler in js/default.js, it would be out of scope anyway. I suppose you could imbed the JavaScript in the markup, but that stinks too.
C# XAML
- Create a Visual Studio C# Windows Store Blank App (XAML), I’m calling mine “simpleEventCS”
- Open MainPage.xaml and paste the following on top of the existing Grid tag (I am using the StackPanel to get it to be more similar to the JS sample above):
<StackPanel Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <TextBlock>Simple Events</TextBlock> <TextBlock Name="_txtHelloText">Button is still Unclicked</TextBlock> <Button Name="_btnUpdateText" Click="_btnUpdateText_Click">Click Me</Button> </StackPanel>
- Double click on “_btnUpdateText_Click” in the Button tag
- Right click on the highlighted text and select Navigate to Event Handler
- Visual Studio will open MainPage.xaml.cs and create an empty even handler named _btnUpdateText_Click, replace that handler (all the way to the first closing bracket ‘}’) with:
// Just for proofiness, I will keep track of clicks and display in the event private int _clickNo = 0; private void _btnUpdateText_Click(object sender, RoutedEventArgs e) { _txtHelloText.Text = "Click #" + (++_clickNo).ToString(); }
NOTE: Yes, the UI for this sample is ugly compared the JavaScript sample above; this is what I get with no styling. It would violate my brain dead simple rule.
No comments:
Post a Comment