wire:init

CBWIRE provides the wire:init directive to initiate actions immediately after a component is rendered on the page. This directive is particularly useful for loading data asynchronously, allowing the rest of the page to load without delay.

Example: Loading Posts on Page Load

Here’s how you can use wire:init to load posts as soon as the component renders, without holding up the loading of the entire page:

component extends="cbwire.models.Component" {

    data = {
        "posts": []
    };

    function loadPosts() {
        // Simulate fetching posts
        data.posts = queryPosts();
    }

    function renderIt() {
        return template( "wires.postsDisplay" );
    }
}

In your postsDisplay view file (wires/postsDisplay.cfm):

<div wire:init="loadPosts">
    <!-- Posts will be displayed here -->
    <cfloop array="#posts#" item="post">
        <p>#post.title#</p>
    </cfloop>
</div>

In this example, the loadPosts method is triggered immediately after the component is rendered, populating the posts array with data fetched from the database. This allows the rest of the page to load uninterrupted while the posts are loaded.

Exploring Further

While wire:init is useful for initiating data load after a component is rendered, lazy loading is often beneficial as an alternative approach, especially for data that isn't required immediately upon page view. Lazy loading can further improve your application's performance and responsiveness.

Last updated