New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

corvid-storeon

Package Overview
Dependencies
Maintainers
1
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

corvid-storeon

A tiny event-based state manager Storeon for Corvid by Wix

2.1.0
Source
npm
Version published
Weekly downloads
2
Maintainers
1
Weekly downloads
 
Created
Source

corvid-storeon

corvid-storeon test status npm version

Corvid Storeon

A tiny event-based state manager Storeon for Corvid by Wix.

How to use

You can use demo template or install from Package Manager.

  • Wix Website Template: Open In Editor
  • Install

Example

public/store.js

import { createStore } from "corvid-storeon";

const counter = (store) => {
  store.on("@init", () => ({ count: 0 }));
  store.on("increment", ({ count }) => ({ count: count + 1 }));
};

export const { getState, dispatch, connect, connectPage } = createStore([counter]);

Page Code

import { dispatch, connect, connectPage } from "public/store.js";

// Subscribe for state property "count".
// The callback function will be run when the page loads ($w.onReady())
// and each time when property "count" would change.
connect("count", ({ count }) => {
  $w("#text1").text = String(count);
});

// Wrapper around $w.onReady()
// The callback function will be run once.
connectPage((state) => {
  $w("#button1").onClick(() => {
    // Emit event
    dispatch("increment");
  });
});

Install

You use the Package Manager to manage the npm packages in your site.

Latest available version: v1.1.0

Install corvid-storeon

API

createStore

Creates a store that holds the complete state tree of your app and returns 4 methods for work with the app state. Create Store modules API.

const { getState, dispatch, connect, connectPage } = createStore(modules);
  • createStore(Array<Module>): Store

getState

Returns an object that holds the complete state of your app.

const state = getState();
  • getState(): object

dispatch

Emits an event with optional data.

dispatch("event/type", { value: 123 });
  • dispatch(event: string, [data: any]): void

connect

Connects to state by property key. It will return the function disconnect from the store.

const disconnect = connect("key", (state) => { });

disconnect();

You can connect for multiple keys, the last argument must be a function.

connect("key1", "key2", (state) => { });
  • connect(key: string, [key: string, ...], handler: ConnectEventHandler): Disconnect
  • callback ConnectEventHandler(state: object): void
  • function Disconnect(): void

connectPage

Sets the function that runs when all the page elements have finished loading. (wrapper around $w.onReady())

connectPage((state) => { });
  • connectPage(initFunction: ReadyHandler): void
  • callback ReadyHandler(state: object): void

Store

The store should be created with createStore() function. It accepts a list of the modules.

Each module is just a function, which will accept a store and bind their event listeners.

import wixWindow from "wix-window";
import { createStore } from "corvid-storeon";

// Business logic
function appModule(store) {
  store.on("@init", () => {
    return {
      items: [],
    };
  });

  store.on("items/add", ({ items }, item) => {
    return {
      items: items.concat(item),
    };
  });
}

// Devtools
function logger(store) {
  store.on("@dispatch", (state, [event, data]) => {
    if (event === "@changed") {
      const keys = Object.keys(data).join(', ');
      console.log(`changed: ${keys}`, state);
    } else if (typeof data !== "undefined") {
      console.log(`action: ${event}`, data);
    } else {
      console.log(`action: ${event}`);
    }
  });
}

export default createStore([
  appModule,
  (wixWindow.viewMode === "Preview" && logger),
]);

The store has 3 methods:

  • store.get() will return current state. The state is always an object.
  • store.on(event, callback) will add an event listener.
  • store.dispatch(event, data) will emit an event with optional data.

Events

There are 4 built-in events:

@init

It will be fired in createStore(). The best moment to set an initial state.

store.on("@init", () => { });

@ready

Added in: v2.0.0

It will be fired in $w.onReady() when all the page elements have finished loading.

store.on("@ready", (state) => { });

@dispatch

It will be fired on every new action (on store.dispatch() calls and @changed event). It receives an array with the event name and the event’s data. Can be useful for debugging.

store.on("@dispatch", (state, [event, data]) => { });

@changed

It will be fired when any event changes the state. It receives object with state changes.

store.on("@changed", (state, data) => { });

You can dispatch any other events. Just do not start event names with @.

Reducers

If the event listener returns an object, this object will update the state. You do not need to return the whole state, return an object with changed keys.

// "products": {} will be added to state on initialization
store.on("@init", () => {
  return { products: { } };
});

Event listener accepts the current state as a first argument and optional event object as a second.

So event listeners can be a reducer as well. As in Redux’s reducers, you should change immutable.

store.on("products/save", ({ products }, product) => {
  return {
    products: { ...products, [product._id]: product },
  };
});
$w("#buttonAdd").onClick(() => {
  dispatch("products/save", {
    _id: uuid(),
    name: $w("inputName").value,
  });
});

Async operations

You can dispatch other events in event listeners. It can be useful for async operations.

store.on("products/add", async (_, product) => {
  try {
    await wixData.save("Products",  product);

    store.dispatch("products/save", product);
  } catch (error) {
    store.dispatch("errors/database", error);
  }
});

Unbind listener

store.on() returns cleanup function. This function will remove the event listener.

const unbind = store.on("@changed", () => { });

unbind();

License

MIT

Keywords

wix

FAQs

Package last updated on 02 Mar 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts