GithubHelp home page GithubHelp logo

ljbc1994 / blazorintersectionobserver Goto Github PK

View Code? Open in Web Editor NEW
60.0 4.0 12.0 1.15 MB

🔎 Intersection Observer API wrapper for Blazor applications

License: MIT License

TypeScript 37.87% JavaScript 12.36% C# 49.66% HTML 0.11%
blazor intersectionobserver typescript intersectionobserver-api

blazorintersectionobserver's Introduction

BlazorIntersectionObserver

Package Version NuGet Downloads License

A comprehensive wrapper around the Intersection Observer API, giving you all the goodness of observing intersections in a performant way.

This is a wrapper around the Intersection Observer API so that you can use it in Blazor for .NET 5. It has the same API structure with convenience methods and components for a better dev experience. It works with both Blazor WebAssembly and Blazor Server.

Get Started

1. Installation

Install BlazorIntersectionObserver through NuGet.

> dotnet add package BlazorIntersectionObserver

2. Register the service

Now you'll need to add the service to the service configuration.

WebAssembly (Program.cs)

using Ljbc1994.Blazor.IntersectionObserver;

public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.Services.AddIntersectionObserver();
    }
}

OR

Server (Startup.cs)

using Ljbc1994.Blazor.IntersectionObserver;

public class Startup {
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddIntersectionObserver();
    }
}

3. Use it!

For the quickest setup, use the IntersectionObserve component. This provides an implicit context object which contains the observer entry! Easy!

Component setup

@using Ljbc1994.Blazor.IntersectionObserver.Components

<IntersectionObserve>
    <div @ref="context.Ref.Current">
        Hey... I'm @(context.IsIntersecting ? "in view": "out of view")
    </div>
</IntersectionObserve>

OR

Service setup

To directly use the service, you just need to inject it and observe the element(s).

@using Ljbc1994.Blazor.IntersectionObserver
@inject IIntersectionObserverService ObserverService

<img @ref="ImageElement" src="@(IsIntersecting ? "https://www.placecage.com/g/500/500" : "")"/>

@functions {
    public ElementReference ImageElement { get; set; }
    public bool IsIntersecting { get; set; }
    
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender) 
        {
            await SetupObserver();
        }
    }

    public async void SetupObserver()
    {
        await ObserverService.Observe(ImageElement, (entries) =>
        {
            var entry = entries.FirstOrDefault();
            IsIntersecting = entry.IsIntersecting;
            StateHasChanged();
        });
    }
}

Documentation and Usage

Options

You can pass through options to the ObserverService methods, these are the same as the Intersection Observer API options.

Example

var options = new IntersectionObserverOptions {
    Root = BodyRef, 
    Threshold = new List<double> { 0.25, 0.5, 1 },
    RootMargin = "10px 10px 10px 10px"
};

Service Methods

Observe

This a shorthand way of observing an element by providing:

  • The element you want to observe.
  • The callback to trigger on an intersection update.
  • The intersection observer options.

This returns an IntersectionObserver instance, allowing you to disconnect the observer or unobserve an element. Or if you wish, observe additional elements.

var observer = await ObserverService.Observe(ElementRef, (entries) => {
    IsIntersecting = entries.FirstOrDefault().IsIntersecting;
    StateHasChanged();
}, options);

Create

The Create method follows the same approach as the Intersection Observer API, you create the observer and then pass elements you wish to observe by calling the Observe method on the observer instance. To create the observer, provide the following:

  • The callback to trigger on an intersection update.
  • The intersection observer options.

This returns an IntersectionObserver instance, allowing you to Observe elements. This also provides the ability to disconnect or unobserve the element.

var observer = await ObserverService.Create((entries) => {
    IsIntersecting = entries.FirstOrDefault().IsIntersecting;
    StateHasChanged();
}, options);

await observer.Observe(FirstImage);
await observer.Unobserve(FirstImage);

IntersectionObserver Methods

Observe

To observe an element, provide the element reference to the IntersectionObserver instance by calling Observe.

observer.Observe(ElementReference);

Unobserve

To unobserve an element, provide the element reference to the IntersectionObserver instance by calling Unobserve.

observer.Unobserve(ElementReference);

Disconnect

To disconnect the observer, call Disconnect on the IntersectionObserver instance.

observer.Disconnect();

This will remove all the observed elements from the observer, i.e.

@using Ljbc1994.Blazor.IntersectionObserver
@implements IAsyncDisposable
@inject IIntersectionObserverService ObserverService

<div @ref="ImageRef"></div>

@functions {
    private IntersectionObserver Observer;
    @* Code... *@

    public async ValueTask DisconnectAll()
    {
        if (this.Observer != null)
        {
            await this.Observer.Disconnect();
        }
    }
}

Dispose

To remove the observer, call Dispose on the IntersectionObserver instance.

observer.Dispose();

This is a useful method to clean up observers when components are disposed of, i.e.

@using Ljbc1994.Blazor.IntersectionObserver
@implements IAsyncDisposable
@inject IIntersectionObserverService ObserverService

<div @ref="ImageRef"></div>

@functions {
    private IntersectionObserver Observer;
    @* Code... *@

    public async ValueTask DisposeAsync()
    {
        if (this.Observer != null)
        {
            await this.Observer.Dispose();
        }
    }
}

Component

<IntersectionObserve>

Rather than directly interfacing with the service, you can use this convenience component for quick and easy observing. You can access the observer entry through the implicit @context!

You need to make sure to provide the reference of the element you want to observe, this is done by passing the element reference to the context reference.

@* Injecting service... *@

<IntersectionObserve>
    <div @ref="context.Ref.Current">
        Hey... look I'm @(context.IsIntersecting ? "intersecting!": "not intersecting!")
    </div>
</IntersectionObserve>

@* Component code... *@
Props
  • OnChange (EventCallback<IntersectionObserverEntry>) - When the intersection observer has a entry update.
  • IsIntersecting (bool) - Whether the element is intersecting - used for two-way binding.
  • Options (IntersectionObserverOptions) - The options for the observer.
  • Once (bool) - Only observe once for an intersection, then the instance disposes of itself.

Context

The context is the IntersectionObserverContext object, with the following signature:

public class IntersectionObserverContext 
{
    public IntersectionObserverEntry Entry { get; set; }
    public ForwardReference Ref { get; set; } = new ForwardReference();
    public bool IsIntersecting => this.Entry?.IsIntersecting ?? false;
}

public class IntersectionObserverEntry
{
    public bool IsIntersecting { get; set; }

    public double IntersectionRatio { get; set; }

    public DOMRectReadOnly BoundingClientRect { get; set; }

    public DOMRectReadOnly RootBounds { get; set; }

    public bool IsVisible { get; set; }

    public double Time { get; set; }
}

Additional Information

Upgrading to 2.0.1+

In versions prior to 2.0.1, the IntersectionObserve component didn't require a reference to the node as it was wrapped in an element that was automatically observed. This was changed to ensure the consumer provides the reference to prevent any potential layout issues and make it explicit what element should be observed.

Therefore, before 2.0.1, if the consumer had an element with display: none; within the IntersectionObserve component, this would have worked. However, as we're now observing the element provided as opposed to a wrapped element, this will no longer work. To resolve this, you can wrap the observed element in a div and observe the container div instead of the observed element.

Feature Requests

There's so much that IntersectionObserver can do, so if you have any requests or you want better documentation and examples, feel free to make a pull request or create an issue!

blazorintersectionobserver's People

Contributors

dependabot[bot] avatar epicturkey avatar gavin2n avatar ljbc1994 avatar w8api avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

blazorintersectionobserver's Issues

Improved error checking and feedback

Is your feature request related to a problem? Please describe.
We had some trouble getting back on track after upgrading from a very early version to a later one. There are some important usage guidelines that ought to be more explicitly documented and and error checked.

From the documentation:
<IntersectionObserve> <div @ref="context.Ref.Current"> Hey... I'm @(context.IsIntersecting ? "in view": "out of view") </div> </IntersectionObserve>

While upgrading from an earlier version we noted the following issues:

  • If the <div> element is missing (i.e. <IntersectionObserve ... />) the component will fail runtime with an obscure "Element doesn't implement interface" message or similar
  • If the <div> element doesn't have the @ref="context.Ref.Current" markup it will fail runtime with a confusing null-ref exception
  • If the <div> element isn't rendered (i.e. style=display:none) the observer will not be triggered. This is different from earlier versions.

Although the documented exact usage works fine it would probably be a good idea to error check these caveats and give meaningful debugging feedback with relevant exceptions!

Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'

Hello,

I got the following error in the console after the execution of the logic after checking is the current item is observed.

Microsoft.JSInterop.JSException: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.
TypeError: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.

I apply the code which I use.

<div @ref="@this.Reference">
    Some data
</div>

public ElementReference Reference { get; set; } = new ElementReference(Guid.NewGuid().ToString());

await ObserverService.Observe(Reference, async (entries) =>
{
    if (entries.FirstOrDefault().IsIntersecting)
    {
        // Login execution
    }
});

Regards,
Simeon Valev

How to use BlazorIntersectionObserver inside an iframe?

Hello,

I would like to ask how do I go about in using the component inside an iframe?

I tried to run the Blazor.IntersectionObserver.Client project in my local environment and it works as expected. But when I try to embed the URL of the project in an iframe in a different html page, the BlazorIntersectionObserver no longer works.

Please see the video below:

BlazorIntersectionObserver-IFrame-Issue.mp4

An exception can also be seen in the browser console

BlazorIntersectionObserver-IFrame-Issue-Console-Error

This is the source of the iframe html page.

<html>
<head><title>Test Iframe for Blazor 1</title></head>
<body>		
    <iframe src="https://localhost:5001/" height="1200" width="800" title="Iframe Example"></iframe> 
</body>
</html>

Thank you in advance for your advice

Delay JSInterop until after prerender

In a Blazor-Server setup I get the following error during startup:

System.InvalidOperationException: JavaScript interop calls cannot be issued at this time. This is because the component is being statically rendered. When prerendering is enabled, JavaScript interop calls can only be performed during the OnAfterRenderAsync lifecycle method.
         at Microsoft.AspNetCore.Components.Server.Circuits.RemoteJSRuntime.BeginInvokeJS(Int64 asyncHandle, String identifier, String argsJson, JSCallResultType resultType, Int64 targetInstanceId)
         at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, CancellationToken cancellationToken, Object[] args)
         at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, Object[] args)
         at Blazor.IntersectionObserver.IntersectionObserverService.DisposeAsync()
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.<DisposeAsync>g__Await|15_0(Int32 i, ValueTask vt, List'1 toDispose)
         at Microsoft.AspNetCore.Http.Features.RequestServicesFeature.<DisposeAsync>g__Awaited|9_0(RequestServicesFeature servicesFeature, ValueTask vt)
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.<FireOnCompleted>g__ProcessEvents|227_0(HttpProtocol protocol, Stack'1 events)

To reproduce the error, simply add the <IntersectionObserve> component to a Blazor (.razor) component and launch the Blazor Server app. Unfortunately I don't have a small repro project right now, I could get back to you with one should it still be needed.

NB: It still works, it's just flooding my error log with unsightly call stacks. I have worked around the problem by flagging a bool in my own OnAfterRenderAsync() and only including the <IntersectionObserve> component conditionally when that flag is set. Still, this should probably be handled more centrally in the IntersectionObserve component itself.

More information and simple examples can be found here: https://docs.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-5.0#detect-when-a-blazor-server-app-is-prerendering

JSInterop error on circuit disposal in .NET 6

Describe the bug
An exception is thrown during the Dispose handler of the IntersectionObserve component when the circuit itself is being disposed.

warn: Microsoft.AspNetCore.Components.Server.Circuits.RemoteRenderer[100]
      Unhandled exception rendering component: JavaScript interop calls cannot be issued at this time. This is because the circuit has disconnected and is being disposed.
      Microsoft.JSInterop.JSDisconnectedException: JavaScript interop calls cannot be issued at this time. This is because the circuit has disconnected and is being disposed.
         at Microsoft.AspNetCore.Components.Server.Circuits.RemoteJSRuntime.BeginInvokeJS(Int64 asyncHandle, String identifier, String argsJson, JSCallResultType resultType, Int64 targetInstanceId)
         at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, CancellationToken cancellationToken, Object[] args)
         at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, Object[] args)
         at Ljbc1994.Blazor.IntersectionObserver.IntersectionObserverService.RemoveObserver(String id)
         at Ljbc1994.Blazor.IntersectionObserver.IntersectionObserver.Dispose()
         at Ljbc1994.Blazor.IntersectionObserver.Components.IntersectionObserve.DisposeAsync()
         at Microsoft.AspNetCore.Components.RenderTree.Renderer.<>c__DisplayClass69_0.<<Dispose>g__HandleAsyncExceptions|1>d.MoveNext()

Everything still works fine after the exception, but it fills up the error log with unnecessary error messages.

To Reproduce

  1. Create a page that contains the IntersectionObserve component
  2. Refresh or close the page
  3. An exception will be logged to the error logs

Expected behavior
Catch and silently ignore the exception since we don't need to dispose of the observer if the browser is being closed anyway.

System Info

  • Blazor Server
  • .NET 6

Additional context
This was caused by a changed to Blazor that prevents JS Interop actions during circuit disposal: dotnet/aspnetcore#32901

"Blazor.*" namespace causes a lot of compatibility friction

Describe the bug

Due to the way namespaces are resolved, It's impossible to reference any components from this library in any project that contains *.Blazor.* anywhere in the namespace, because there is no unique path to scope to this assembly, so it will try to resolve from the parent project instead.

@using Blazor.IntersectionObserver

will throw

- The type or namespace name 'IntersectionObserver' does not exist in the namespace 'MyCompany.Blazor' 
- (are you missing an assembly reference?) [E:\Test\MyCompany.Blazor.MyProject\MyCompany.Blazor.MyProject.csproj]

To Reproduce

  1. Create new project where namespace includes Blazor in it
PS> dotnet new blazorwasm -n MyCompany.Blazor.MyProject
  1. Add reference to BlazorIntesectionObserver
PS> cd MyCompany.Blazor.MyProject
PS> dotnet add package BlazorIntersectionObserver
  1. Add using to _Imports.razor
@using Blazor.IntersectionObserver
  1. Build the project
PS> dotnet build

Expected behavior

It should be possible to reference components in this library through unique namespace scope that is not commonly used eg.

@using Ljbc1994.Blazor.IntersectionObserver

Additional context

dotnet/razor#7670

Delay

Hi there,

great stuff, thank you!

Is there a delay as a parameter available, so that the IntersectionObserver triggers context.IsIntersecting only after that delay in ms?

When there are 2 observed components on a page and we quickly scroll down to the lower one using jQuery/anchors, I found out that I get a NullReferenceError of the upper component, cause we intersect the upper component on scrolling for a split second on our way to the lower component.

Cheers,
FM

Failed to fetch dynamically imported module

When publishing my project the blazor-intersection-observer.min.js fails to load.

      Unhandled exception rendering component: Failed to fetch dynamically imported module: https://*.com/_content/BlazorIntersectionObserver/blazor-intersection-observer.min.js
      TypeError: Failed to fetch dynamically imported module: https://*.com/_content/BlazorIntersectionObserver/blazor-intersection-observer.min.js
Microsoft.JSInterop.JSException: Failed to fetch dynamically imported module: https://*.com/_content/BlazorIntersectionObserver/blazor-intersection-observer.min.js
TypeError: Failed to fetch dynamically imported module: https://*.com/_content/BlazorIntersectionObserver/blazor-intersection-observer.min.js
   at Microsoft.JSInterop.JSRuntime.<InvokeAsync>d__16`1[[Microsoft.JSInterop.IJSObjectReference, Microsoft.JSInterop, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].MoveNext()
   at Ljbc1994.Blazor.IntersectionObserver.IntersectionObserverService.Observe(ElementReference element, Action`1 onIntersectUpdate, IntersectionObserverOptions options)
   at *.Frontend.Shared.MainLayout.SetupObservers()
   at *.Frontend.Shared.MainLayout.OnAfterRenderAsync(Boolean firstRender)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task , ComponentState )

At a glance it could be that instead of /_content/BlazorIntersectionObserver/blazor-intersection-observer.min.js it should be ./_content/BlazorIntersectionObserver/blazor-intersection-observer.min.js at

private readonly string scriptPath = "/_content/BlazorIntersectionObserver/blazor-intersection-observer.min.js";

Doesn't work with prerendering

When using ASP.NET Core hosted Blazor WebAssembly app it's possible to make use of server prerendering. With this technique first user request is responded to by server instantaneously with full page html. This is useful for SEO and fast content delivery while app is still downloading in the background. Since prerendering happens only on the server with no connection to the browser, it's invalid to call any JS Interop at that time.

- InvalidOperationException: JavaScript interop calls cannot be issued during server-side prerendering, 
- because the page has not yet loaded in the browser. Prerendered components must wrap any JavaScript 
- interop calls in conditional logic to ensure those interop calls are not attempted during prerendering.

- Blazor.IntersectionObserver.IntersectionObserverService..ctor(IJSRuntime jsRuntime) in IntersectionObserverService.cs
-    27. this.moduleTask = jsRuntime.InvokeAsync<IJSObjectReference>("import", this.scriptPath).AsTask();

Steps to reproduce the behavior:

https://docs.microsoft.com/en-us/aspnet/core/blazor/components/prerendering-and-integration?view=aspnetcore-5.0&pivots=webassembly

Expected behavior

Import JS module only when component is rendered in the browser.

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        if (module == null)
        {
            module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "...");            
        }
    }
}

cannot convert from 'method group' to 'bool'

Hello,

Tx for you work. Great package !

  • I have a compile error: error CS1503: Argument 3: cannot convert from 'method group' to 'bool' and
  • Rider version don't recognize the component
  • I'm obliged to put "global::" in @using

I successfully ran the samples of this repo with expected result point of view Rider and browser.
Then I follow the get started guide to use it in my project:

  • install nuget
  • setup client/program.cs
  • add the import in page, component, code:
    @using global::Blazor.IntersectionObserver

@Inject IIntersectionObserverService ObserverService
...

...

...
public async void OnIntersectingChanged(IntersectionObserverEntry entry)
{
if (entry.IsVisible)
{
Logger.LogInformation("Entry visible");
}
else
{
Logger.LogInformation("Entry not visible");
}
}

  • macOs
  • JetBrains Rider latest version
  • Dotnet 5
  • Blazor web assembly

Tx for your help.

Kind regards,

Michael

This codes brings the observed div into view on load, not desired

Updated, part of the code was not shown in the first post.

First thank you for the great work,

I have 1 issue with the code usage:

Tried this:

<IntersectionObserve> @{var isIntersecting = context.IsIntersecting;} <div @ref="context.Ref.Current" class="wrap @(isIntersecting ? "wrapActive" : "")">

...

The issue is that it always brings the div into the view on load of the page!
Do you know what is causing this or what can be the issue?

Regards!

ElementRef does not exist

Describe the bug
Currently, this library uses Microsoft.AspNetCore.Components.ElementRef, however, it seems like it is Microsoft.AspNetCore.Components.ElementReference, that is needed, as such, there is an error stating that ElementRef does not belong to Microsoft.AspNetCore.Components. I am using Blazor server-side, if that matters?

To Reproduce
Steps to reproduce the behavior:

  1. In visual studio (latest stable version), create a Blazor server-side app
  2. Install BlazorintersecttionObserver via NuGet
  3. set up the service setup sample given in the readme.
  4. See error

Expected behavior
The library should work without having to change/modify types

Desktop (please complete the following information):

  • OS: Windows
  • Browser N/A

Uncaught TypeError: Cannot read properties of null (reading 'x')

Describe the bug
TypeError exception occurs when we navigate back while observing a blazor component.

To Reproduce
Steps to reproduce the behavior:

  1. Go to a page with a blazor component that is being observed.
  2. Navigate back using JSRuntime.InvokeVoidAsync("history.go", "-1");
  3. See error

Expected behavior
No exception when navigating back

Screenshots
image
Uncaught TypeError TypeError: Cannot read properties of null (reading 'x')
at t (C:\Users\######\.nuget\packages\blazorintersectionobserver\3.1.0\staticwebassets\blazor-intersection-observer.min.js:1:255)
at (C:\Users\######\.nuget\packages\blazorintersectionobserver\3.1.0\staticwebassets\blazor-intersection-observer.min.js:1:528)
at (C:\Users\######\.nuget\packages\blazorintersectionobserver\3.1.0\staticwebassets\blazor-intersection-observer.min.js:1:545)
at (C:\Users\######\.nuget\packages\blazorintersectionobserver\3.1.0\staticwebassets\blazor-intersection-observer.min.js:1:210)

Desktop (please complete the following information):

  • OS: [Windows]
  • Browser [Chrome/Edge/Firefox]
  • Version [110.0.5481.177/110.0.1587.50/110.0]

Additional context
I can't reproduce this issue on my machine, but it happens every time on my colleague's machine. We'll provide an update on this when we have more details.

Give data to IntersectionObserve component and get it back in OnChange event

Hello,

I have a list of messages displayed as consecutive divs, each surrounded by a IntersectionObserve component.
I want to mark the message as read when becomes visible (API call).

How can I identify which message is concerned in the OnIntersectingChanged(IntersectionObserverEntry obj) event ?
How can I store the ID of the message in the IntersectionObserve Component

Won't it be possible to add something like a Data attribute that will be stored in the IntersectionObserve div and pass it back from Javascript to the IntersectionObserverEntry ?

Kind regards,

Michael

How to identify the observed target in the callback.

Hi,
I have a group of dynamic elements that I load on a page. Each of them is contained in an IntersectionObserve where I specify the options and the callback. It is working perfectly. However when I am in the callback function I have no way of determining which of the elements the callback is from (other than the bounding box from the entry). Am I missing something? I need to call a C# function from the callback and I need to know which of the elements it is for.

Thanks,
Bob

Could not find file blazor-intersection-observer.js

Hello,

At compilation I get the following error.
In the file system, the file blazor-intersection-observer.min.js exists at the right place.
Renaming it to blazor-intersection-observer.js suppress the error.

Microsoft.NET.Sdk.BlazorWebAssembly.ServiceWorkerAssetsManifest.targets(68, 5): [MSB4018] The "GenerateServiceWorkerAssetsManifest" task failed unexpectedly.
System.AggregateException: One or more errors occurred. (Could not find file '/XXXX/.nuget/packages/blazorintersectionobserver/2.0.0/staticwebassets/blazor-intersection-observer.js'.)
---> System.IO.FileNotFoundException: Could not find file '/XXXX/.nuget/packages/blazorintersectionobserver/2.0.0/staticwebassets/blazor-intersection-observer.js'.
File name: '/XXXX/.nuget/packages/blazorintersectionobserver/2.0.0/staticwebassets/blazor-intersection-observer.js'
at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func2 errorRewriter) at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String path, OpenFlags flags, Int32 mode) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) [...] at System.Threading.Tasks.Parallel.For(Int32 fromInclusive, Int32 toExclusive, Action1 body)
at Microsoft.NET.Sdk.BlazorWebAssembly.GenerateServiceWorkerAssetsManifest.GenerateAssetManifest(Stream stream)
at Microsoft.NET.Sdk.BlazorWebAssembly.GenerateServiceWorkerAssetsManifest.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask(ITaskExecutionHost taskExecutionHost, TaskLoggingContext taskLoggingContext, TaskHost taskHost, ItemBucket bucket, TaskExecutionMode howToExecuteTask)

  • OS: OSx

using ObserverService throws an exception

Hi

I have a loader at the end of the page.
When the user scrolls to to the end of the page, I want the loader to no more observe untill new data is loaded.
And observe again once new data loaded.
Here is my code:

public async Task SetupObserver()
{
   endOfListObserver = await ObserverService.Create(async (entries) => {
    IsIntersecting = entries.FirstOrDefault().IsIntersecting;
    Console.WriteLine("IsIntersecting...");
    if (!IsLoading)
    {
      if (IsIntersecting)
      {
        await endOfListObserver.Unobserve(LoaderElement);
        Console.WriteLine("unobserve");
        var canAddMore = await LoadData();
        StateHasChanged();
        if (canAddMore)
        {
          await endOfListObserver.Observe(LoaderElement);
          Console.WriteLine("observe");
        }
      }
    }   
  });

  await endOfListObserver.Observe(LoaderElement);
}

html code is just

 <span @ref="LoaderElement">Please wait</span>

But an error is throwned when trying to unobserve :
Microsoft.JSInterop.JSException : 'An exception occurred executing JS interop: The JSON value could not be converted to System.Boolean. Path: $ | LineNumber: 0 | BytePositionInLine: 4.. See InnerException for more details.'
InvalidOperationException : Cannot get the value of a token type 'Null' as a boolean.

Any idea ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.