simplajs / simpla

Open, modular, and serverless content management for a modern web
https://www.simplajs.org
MIT License
527 stars 36 forks source link

[2.0] Add query observer #57

Closed bedeoverend closed 7 years ago

bedeoverend commented 7 years ago

Adds in observeQuery which registers a callback that gets called everytime a query's results change. It is to find as observe is to get.

For example:

function renderPostIndex(response) {
  let toPostPreview = (item) => `
<a href="?post=${item.path}">
  <div>${item.data.preview}</div>
</a>
`;

  this.innerHTML = response.items.map(toPostPreview);
}

function addPost(name, preview) {
  Simpla.set(`/posts/${name}`, {
    data: { preview }
  });
}

Simpla.observeQuery({ parent: '/posts' }, renderPostIndex);
Simpla.find({ parent: '/posts' }).then(renderPostIndex);

This above snippet would render all posts by making an initial query, and then watching to see if any more posts are added. Calling addPost would add a new post into Simpla, adding a new item post preview onto the page.