Component rendering logic requiring javascript interop with ElementRef
I am stuck with the following problem in a component library I am developing. I want to expose an "Func<ElementRef,bool> EnabledHandler" parameter in my component, because the consumer of the component is expected to decide whether the component should be enabled or not based on some Javascript logic that includes the element reference.
Because I am dependent on the ElementRef I tried to insert the logic in the OnAfterRender event, however it is too late in the component's lifecycle to change the rendered html.
Let me elaborate, consider the following example:
Index.cshtml
<div>
<DynamicButton EnabledHandler="@DynamicEnabled" />
</div>
<span>
<DynamicButton EnabledHandler="@DynamicEnabled" />
</span>
@functions{
bool DynamicEnabled(ElementRef element)
{
//Do some javascript stuff with the element and decide if the component should be enabled
return RegisteredFunction.Invoke<bool>("buttonEnabledLogic", element); ;
}
}
Javascript
<script>
Blazor.registerFunction('buttonEnabledLogic', function (elem) {
//some example js logic that requires the element
return elem.parentNode.nodeName == "DIV";
});
</script>
DynamicButton.cshtml
<button ref="@ButtonRef" disabled="@(!Enabled)">I am dynamically enabled</button>
@functions{
ElementRef ButtonRef;
bool Enabled { get; set; } = true;
[Parameter]
Func<ElementRef, bool> EnabledHandler { get; set; }
protected override void OnAfterRender()
{
//The EnabledHandler requires ButtonRef to be populated, so
//it must be OnAfterRender
var oldEnabledValue = Enabled;
if (EnabledHandler != null)
{
Enabled = EnabledHandler(ButtonRef);
}
if (oldEnabledValue != Enabled)
{
//This does not work
StateHasChanged();
}
}
}
Any suggestions/workarounds ? Thanks in advance
After the JS event handler returns value, instead of checking if the enabled value is same as before, try setting a property on the control in the index.cshtml page. that would work, Take a look at aspnet/Blazor#761
@dlr1 Yes, I know, that would work, but in my case this is not possible, at least as far as I understand. In my real code I have a component that reacts to right click mouse events and triggers an other component so I don't have direct references of one component to the other.
Here is my library if you would like more info: https://github.com/stavroskasidis/BlazorContextMenu
This looks really cool from the animation in your readme file :)
Unfortunately I don't understand why you want to make the "enabled" decision based on a DOM element. I'm sure you have a good reason but I haven't understood what it is. If you were able to change your EnabledHandler so that it doesn't try to make decisions in terms of data from the DOM, it would be simpler, more flexible, and better performing. The benefits would be:
- Only need to render once. Your current approach of of rendering (so that an HTML element exists), then running some more logic, then rendering again, will at least double the number of renders.
- Being compatible with unit testing and server-side rendering once those are implemented. Any code that is coupled to the DOM will not be able to run in those environments so should be minimised.
Is the basic issue to do with trying to communicate between components? Is there any chance you could sketch out what kinds of communication is happening between your components and what stops them from doing so purely in terms of data held in .NET (not the DOM)?
Wow thanks for the answer @SteveSandersonMS . You are right, the basic issue is communication between components.
I have 2 main components in my library, the ContextMenu and the ContextMenuTrigger. The two components are "bound" (loosely) by the ContextMenu id (required param).
Example from README.MD
<ContextMenu Id="myMenu">
<Item Click="@OnClick">Item 1</Item>
<Item Click="@OnClick">Item 2</Item>
<Item Click="@OnClick" Enabled="false">Item 3 (disabled)</Item>
<Seperator />
<Item>Submenu
<SubMenu>
<Item Click="@OnClick">Submenu Item 1</Item>
<Item Click="@OnClick">Submenu Item 2</Item>
</SubMenu>
</Item>
</ContextMenu>
<ContextMenuTrigger MenuId="myMenu">
<p>Right-click on me to show the context menu !!</p>
</ContextMenuTrigger>
In the current design, the ContextMenuTrigger component is just a wrapper that captures the oncontextmenu event. Any right click in the child components will trigger the menu show. The two components communicate through javascript interop, because they are loosely tied together by an id reference.
The feature that I am trying to implement is having a ContextMenu Item enabled or disabled, depending on the source element clicked. For example, right-clicking on a grid row that cannot be deleted, the "Delete" item should be disabled.
I am currently missing a way to communicate between components that do not have a direct reference with one-another (ergo, the js interops) or capture references to any components in the @ChildContent property. However, I understand that there may be a flaw in my design.
Maybe templating is more appropriate for this component case and I will give it a try when that is available at some point.
Thank you for your time, I know its limited :)
OK, since your goal is to have a way of locating component instances, I'd recommend implementing a central store for them. Example:
ContextMenuStore.cs
public static class ContextMenuStore
{
public static Dictionary<string, ContextMenu> _activeContextMenus
= new Dictionary<string, ContextMenu>();
public static void Register(string id, object contextMenu)
=> _activeContextMenus.Add(id, (ContextMenu)contextMenu);
public static void Unregister(string id)
=> _activeContextMenus.Remove(id);
public static ContextMenu Find(string id)
=> _activeContextMenus[id];
}
ContextMenu.cshtml
@implements IDisposable
@if (isVisible)
{
<h2>@Text</h2>
}
@functions {
bool isVisible;
[Parameter] string ContextMenuId { get; set; }
[Parameter] string Text { get; set; }
protected override void OnInit()
{
ContextMenuStore.Register(ContextMenuId, this);
}
public void Dispose()
{
ContextMenuStore.Unregister(ContextMenuId);
}
public void Show()
{
isVisible = true;
StateHasChanged();
}
}
ContextMenuTrigger.cshtml
<div oncontextmenu="@Trigger">
@ChildContent
</div>
@functions {
[Parameter] string ContextMenuId { get; set; }
[Parameter] RenderFragment ChildContent { get; set; }
void Trigger()
{
ContextMenuStore.Find(ContextMenuId).Show();
}
}
This will keep all the communication inside .NET and is hopefully simpler.
I'll close this because hopefully it answers the question. Hope that's OK.
Thank you for the answer Steve. This is like almost exactly the code I have already written :)
Works fine for now. Keep up the good work on the framework !