Add first class support for onclick and other event handlers
What is it?
We're doing some tweaks to the ways that event handlers get wired to DOM events in Blazor, and adding a lot more features and power.
Hooking up a C# function to a handle a DOM event will look like:
<button onclick="@OnClick" />
@functions {
void OnClick(UIMouseEventArgs e)
{
Console.WriteLine("hello, world");
}
}
or if you'd prefer a lambda:
<button onclick="@(e => Console.WriteLine("hello, world"))"
This has first class integration with the editor in Visual Studio and will include tooltips and completion.
Passing in a string like <button onclick="foo" /> will not do any magic, and will work as if it were normal HTML.
What's changing
This kind of thing has been possible today using a few temporary syntaxes that will be removed as part of 0.2. Namely <button @onclick(Foo) /> and `<button onclick=@{ Foo(); } />. This change makes the event handler wire up look and function the same way as other Razor features.
What's added
Along with this change we'll be defining more of the standard DOM events with first class completion and eventargs types.
We'll also be adding support for arbitrary event names. So <button onfoo="@Foo" /> will bind the Foo method to be called when the foo DOM event is fired.
TODO
- [x] Add language support for
onclickandonchange - [x] Remove temporary workarounds
- [x] Support
Actionin addition toUIEventHandler - [x] Add support for arbitrary events
- [x] Remove allocations for common cases
how would passing parameters look like?
for ex; <div onclick="@OnClick(item)"/>
I guess if you use the lambda variant you can do that
<button onclick="@(e => Console.WriteLine("hello, world " + item))"
I should have been more specific. How would the eventhandler be looking like in code/@functions, are the arguments going to be added the handler, is it params argument type, etc
update: did not try, but guess following might work, but cumbersome
<button onclick="@(e => SomeMethod(item))"
Is there any specific syntax for passing the event? Like <div onclick="@OnClick($event)"/>?
@AWulkan just look at the first post, the example shows how to pass event (namely you don't explicitly, you always do). You currently cannot have events not receiving the event argument anymore
@AWulkan
Yes, it's like this: onsomeevent="@(evt => MyCode(evt))", where evt is some subclass of UIEventArgs. The compiler checks you're passing a legal subclass based on the event type.
Alternative just onsomeevent="@MyMethod", where you also have void MyMethod(UIEventArgs args) { ... } (or whatever applicable subclass of UIEventArgs, such as UIChangeEventArgs).