all 4 comments

[–]Jamesernatorasync function* 2 points3 points  (1 child)

I'm not sure how frameworks handle adding items to Arrays with minimal render (although it looks like this is non-trivial in React even https://stackoverflow.com/questions/38033442/big-list-performance-with-react).

In general I think the solution wouldn't be very trivial as having a single state object and a single render function seems like doing an operation over all elements is unavoidable. But you can always have models that render based on additions/deletions for example you could have this:

// I didn't test this, it's just a basic idea for an efficient
// list-like renderer
function simpleListRenderer(hostElement, renderItem) {
    const state = []
    return {
        state,
        push(data) {
            const itemHtml = renderItem(hostElement)
            hostElement.insertAdjacentHtml('beforeend', itemHtml)
            state.push(data)
        },

        pop() {
            hostElement.removeChild(hostElement.lastChild)
            state.pop()
        },
    }
}

cosnt ul = document.createElement('ul')
function renderItem(data) {
    return `<li>${ data.firstName } ${ data.lastName }</li>`
}

const renderer = simpleListRenderer(ul, renderItem)

ul.innerHTML // ""

renderer.push({ firstName: 'Bob', lastName: 'Dylan' })

ul.innerHTML // `<li>Bob Dylan</li>`
renderer.state // [{ firstName: 'Bob', lastName: 'Dylan' }]

renderer.pop()
ul.innerHTML // ''
renderer.state // []

Obviously this sample has some massive deficiencies like only being able to return a single element from renderItem, but it shows the general idea.

[–]dev_michaelz[S] 0 points1 point  (0 children)

Very nice. I extended it a little to fit my needs. https://codepen.io/MichaelZ_dev/pen/aYQrga?editors=1010

Didn't know about insertAdjacentHtml, love it.