Monday, June 13, 2011

Closures, Anonymous: JavaScript influenced C#

{

I’ve taken knocks in the past because of my penchant for closures and lambdas. Syntactically they never looked that strange to me and most of the time when I used them it was because it made more sense to get a sense of the flow of how things were assigned. I thought: this feels so natural, what makes it so different from some of the people I’m around using C#? Here’s an example of how I’d approach something: in the constructor, assign a loading handler, in that handler, assign a click handler, and rather than putting it in some separate method where I’d have to scroll or look elsewhere, just place it here:

        public MainPage()
{
InitializeComponent();

this.Loaded += (o, e) =>
{
myButton.Click += (_, e2) =>
{
myText.Text = "Hello World";
};
};
}


But then the other day I was tinkering with KnockoutJS, writing some Javascript with jquery and it dawned on my why I approach things the way I do.



        $(document).ready(function () {
$('#myButton').click(function () {
$('#myLabel').text('Hello World');
});
});


It's always interesting to make that connection more formally than trying to explain why my approach would be “better.” The advantage of being able to use a closure with the above approach has always been the main rational I’ve given when forced to come up with an answer.



}

No comments: