用Svelte和jQuery DataTable结果反应更新对象,以未知的Promise promand parenthnode null

发布于 2025-02-13 03:28:40 字数 4483 浏览 1 评论 0原文

我正在缓慢但肯定地将一个jQuery项目迁移到Svelte,但是某些功能(例如DataTables)在jQuery中只是更成熟的。因此,引用 svelte html”>来自服务器端调用的对象数组与诺言;然后重新绘制桌子。目的是使实施更接近本地Svelte。
但是,尽管我将表呈现呈现,但是当我用SVELTE插入JQuery搜索功能时,我只能在收到错误之前更新表:undfrach(in Promise)typeerror: e.parentNode为null

有人可以帮助我了解为什么会发生这种情况吗?

// Load.svelte
<script context="module">
    import {env} from './EnvUtils.js';
    import axios from "axios";
    const wait = delay => new Promise(resolve => setTimeout(resolve, delay));
    let perPage = 10;

    console.log(env);

    const BASE_URL = env.host + 'blogged-posts';

    const config = {
        headers: {
            "X-Requested-With": "XMLHttpRequest",
            "Accept": "application/json",
            'Content-Type': 'application/json',
            "X-CSRF-Token": document.querySelector('meta[name="csrf-token"][content]').content
        }
    }

    export async function fetchData(page, search = undefined) {
        await wait(500);
        console.log(page, search);
        try {
            const getUrl = (search!==undefined) ? `${BASE_URL}?page=${page}&per_page=${perPage}&search=${search}&delay=1` : `${BASE_URL}?page=${page}&per_page=${perPage}&delay=1`;
            const response = await axios.get(getUrl, config);
            const { data } = await response;
            console.log("data:", data);
            
            return data && data['data']!==null && data['data']!==undefined ? data.data : [];
        } catch (error) {
            console.error("Error: ", error);
        }
    }
</script>

上面是load.svelte使用axios检索远程数据的模块。

// Blog.svelte
<script>
    import { onMount, tick } from "svelte";
    import {env} from './utils/EnvUtils.js';
    import {fetchData} from "./utils/Load.svelte";
    import jQuery from "jquery/dist/jquery";
    import initDt from 'datatables.net-dt';

    console.log(env, jQuery, initDt);
    let search;
    let currentPage = 1;
    let el // table element
    let table // table object (API)
    
    $: dataPromise = fetchData(currentPage, search);
    
    onMount(() => {
        dataPromise.then(tick).then(() => {
            table = jQuery(el).DataTable();
            // search input function
            table.on('search.dt', function() {
                var input = jQuery('.dataTables_filter input')[0];

                dataPromise = fetchData(table.page.info().page, input.value);

                dataPromise.then(tick).then(() => {  // error occurs within this promise on searching more than one letter
                    console.log("redraw");
                });
            });
        })
    });
</script>
<table bind:this={el} class="display" style="width:100%">
    <thead>
      <tr>
        <th>Title</th>
        <th>Updated</th>
      </tr>
    </thead>
    <tbody>
      {#await dataPromise}
      <tr><td>...fetching</td></tr>
      {:then rows}
        {#each rows as row}
          <tr>
              <td>{row.title}</td>
              <td>{row.updated_at}</td>
          </tr>
        {/each}
      {/await}
    </tbody>
    <tfoot>
      <tr>
        <th>Title</th>
        <th>Updated</th>
      </tr>
    </tfoot>
  </table>

以上是blog.svelte组件,它在呈现数据表之前等待应许datapromise。在搜索 DataTable的输入中;我呼吁fetchdata功能将新数据移交给datapromise时,当搜索词更改时, variale 变量。长期搜索词的承诺将被多次调用,并在完成诺言后多次更新表。
为了克服此问题,我创建了一个Svelte 存储Writable on Readrey变量,以检查承诺是否忙。

// Store.svelte
<script context="module">
    import { writable } from 'svelte/store'

    export const onReady = writable(true)
</script>
// ... amendments Load.svelte
    export async function fetchData(page, search = undefined) {
        onReady = false;
// before return
        onReady = true;

// ... amendments Blog.svelte
// before calling promise in input function check onReady?
       if (!onReady) return false;
       dataPromise = fetchData(table.page.info().page, input.value);

这没有解决问题:有人可以帮忙吗?

I am slowly but surely migrating a jquery project to Svelte, but some features such as datatables are just a bit more mature in jquery. So referencing the Svelte html example I tested the reactive feature of Svelte by updating an Array of objects from a server side call with a promise; and then redrawing the table. The purpose being to bring the implementation closer to native Svelte.
But although I get the table to render, when I plugged the jquery search feature with the Svelte reactively declared variable, I only get to update the table once before I receive an error: Uncaught (in promise) TypeError: e.parentNode is null.

Can someone please help me to understand why this will happen?

// Load.svelte
<script context="module">
    import {env} from './EnvUtils.js';
    import axios from "axios";
    const wait = delay => new Promise(resolve => setTimeout(resolve, delay));
    let perPage = 10;

    console.log(env);

    const BASE_URL = env.host + 'blogged-posts';

    const config = {
        headers: {
            "X-Requested-With": "XMLHttpRequest",
            "Accept": "application/json",
            'Content-Type': 'application/json',
            "X-CSRF-Token": document.querySelector('meta[name="csrf-token"][content]').content
        }
    }

    export async function fetchData(page, search = undefined) {
        await wait(500);
        console.log(page, search);
        try {
            const getUrl = (search!==undefined) ? `${BASE_URL}?page=${page}&per_page=${perPage}&search=${search}&delay=1` : `${BASE_URL}?page=${page}&per_page=${perPage}&delay=1`;
            const response = await axios.get(getUrl, config);
            const { data } = await response;
            console.log("data:", data);
            
            return data && data['data']!==null && data['data']!==undefined ? data.data : [];
        } catch (error) {
            console.error("Error: ", error);
        }
    }
</script>

Above is the Load.svelte module that uses axios to retrieve remote data.

// Blog.svelte
<script>
    import { onMount, tick } from "svelte";
    import {env} from './utils/EnvUtils.js';
    import {fetchData} from "./utils/Load.svelte";
    import jQuery from "jquery/dist/jquery";
    import initDt from 'datatables.net-dt';

    console.log(env, jQuery, initDt);
    let search;
    let currentPage = 1;
    let el // table element
    let table // table object (API)
    
    $: dataPromise = fetchData(currentPage, search);
    
    onMount(() => {
        dataPromise.then(tick).then(() => {
            table = jQuery(el).DataTable();
            // search input function
            table.on('search.dt', function() {
                var input = jQuery('.dataTables_filter input')[0];

                dataPromise = fetchData(table.page.info().page, input.value);

                dataPromise.then(tick).then(() => {  // error occurs within this promise on searching more than one letter
                    console.log("redraw");
                });
            });
        })
    });
</script>
<table bind:this={el} class="display" style="width:100%">
    <thead>
      <tr>
        <th>Title</th>
        <th>Updated</th>
      </tr>
    </thead>
    <tbody>
      {#await dataPromise}
      <tr><td>...fetching</td></tr>
      {:then rows}
        {#each rows as row}
          <tr>
              <td>{row.title}</td>
              <td>{row.updated_at}</td>
          </tr>
        {/each}
      {/await}
    </tbody>
    <tfoot>
      <tr>
        <th>Title</th>
        <th>Updated</th>
      </tr>
    </tfoot>
  </table>

Above is the Blog.svelte component that awaits the promised dataPromise before rendering the datatable. Within the search input of the datatable; I call upon the fetchData function to hand new data to the dataPromise reactively declared variable when the search term is changed. The promise will with long search terms be called multiple times and upon finishing the promise update the table multiple times.
To overcome this issue I created a Svelte store writable onReady variable to check if a promise is busy.

// Store.svelte
<script context="module">
    import { writable } from 'svelte/store'

    export const onReady = writable(true)
</script>
// ... amendments Load.svelte
    export async function fetchData(page, search = undefined) {
        onReady = false;
// before return
        onReady = true;

// ... amendments Blog.svelte
// before calling promise in input function check onReady?
       if (!onReady) return false;
       dataPromise = fetchData(table.page.info().page, input.value);

This did not solve the issue: Can someone please help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦开始←不甜 2025-02-20 03:28:40

您不能仅替换由数据塔管理的HTML。您必须更新基础数据。

当您的数据异步加载时,无论如何都不应该这样做。您应该设置 serverside true并可能使用 ajax 如果您不能或不想实现符合默认请求/符合默认请求/的服务器端点,则提供用于获取和格式数据的自定义功能响应格式。

不这样做也会干扰过滤,默认情况下,这种过滤发生了。当启用服务器端处理时,DataTables还将自动应用400ms的搜索延迟,可以通过 searchDelay 选项。

示例

<script>
    import jQuery from '[email protected]';
    import dt from '[email protected]';
    import { onMount } from 'svelte';
    
    let table;
    let tableApi;
    
    onMount(() => {
        dt(window, jQuery);
        tableApi = jQuery(table).DataTable({
            serverSide: true,
            ajax: async (data, callback, settings) => {
                const json = await fetch('https://jsonplaceholder.typicode.com/posts')
                    .then(r => r.json());
                
                // This should happen on server
                const search = data.search.value;
                const filtered = json.filter(x => !search || x.title.indexOf(search) != -1);
                const page = filtered.slice(data.start).slice(0, data.length);

                // Expected format for callback:
                callback({
                    draw: data.draw,
                    data: page,
                    recordsFiltered: filtered.length,
                    recordsTotal: json.length,
                });
            },
            columns: [
                // Set JSON data source for columns
                { data: 'id' },
                { data: 'title' },
            ]
        });
    })
</script>

<svelte:head>
    <link rel=stylesheet href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css"/>
</svelte:head>

<table id=table bind:this={table}>
    <thead>
        <tr>
            <th>ID</th>
            <th>Title</th>
        </tr>
    </thead>
</table>

: 为此。

Svelte唯一可以/应该使用的时间是,如果列实际包含HTML。为此, columns.renders.render 可以使用功能。不幸的是,不能嵌入组件,并且DataTables API似乎也不提供仅提供整个行的方法,因此每个需要较高的供电渲染的单元格必须将其提取到单独的组件中。

?出于某种原因的重复。)

You cannot just replace HTML that is managed by the Datatables. You would have to update the underlying data instead.

As your data is loaded asynchronously, this should not be done that way anyway. You should set serverSide to true and possibly use ajax to supply a custom function for fetching and formatting the data, if you cannot or do not want to implement a server endpoint that conforms to the default request/response format.

Not doing it this way also interferes with the filtering, which happens client-side by default. When server-side processing is enabled, Datatables will also automatically apply a search delay of 400ms which can be changed via the searchDelay option.

Example:

<script>
    import jQuery from '[email protected]';
    import dt from '[email protected]';
    import { onMount } from 'svelte';
    
    let table;
    let tableApi;
    
    onMount(() => {
        dt(window, jQuery);
        tableApi = jQuery(table).DataTable({
            serverSide: true,
            ajax: async (data, callback, settings) => {
                const json = await fetch('https://jsonplaceholder.typicode.com/posts')
                    .then(r => r.json());
                
                // This should happen on server
                const search = data.search.value;
                const filtered = json.filter(x => !search || x.title.indexOf(search) != -1);
                const page = filtered.slice(data.start).slice(0, data.length);

                // Expected format for callback:
                callback({
                    draw: data.draw,
                    data: page,
                    recordsFiltered: filtered.length,
                    recordsTotal: json.length,
                });
            },
            columns: [
                // Set JSON data source for columns
                { data: 'id' },
                { data: 'title' },
            ]
        });
    })
</script>

<svelte:head>
    <link rel=stylesheet href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css"/>
</svelte:head>

<table id=table bind:this={table}>
    <thead>
        <tr>
            <th>ID</th>
            <th>Title</th>
        </tr>
    </thead>
</table>

REPL

There is no point in using Svelte here, the API is not meant for it.

The only time Svelte can/should be used, is if a column actually contains HTML. For that the columns.render function can be used. Unfortunately components cannot be inlined and the Datatables API also does not appear to offer a method for just rendering an entire row, so each cell that requires Svelte-powered rendering has to be extracted to a separate component.

REPL example with column renderer

(Paging causes new tabs to be opened in the REPL for some reason.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文