jeffmitchel / meteor-local-persist

Persistent client (browser) collections for Meteor, using localStorage.
Other
33 stars 11 forks source link

Meteor Local Persist Package

Persistent client (browser) collections for Meteor, using localStorage. Collections are reactive across browser tabs.

Installation:

meteor add jeffm:local-persist

Documentation:

Constructor:

LocalPersist(collection, key, options);

Options:

Methods:

  None.

Dependancies:

Notes:

Example:

Implement a simple shopping cart as a local collection.

if (Meteor.isClient) {
    // create a local collection
    var shoppingCart = new Meteor.Collection(null);

    // create a local persistence observer
    var shoppingCartObserver = new LocalPersist(shoppingCart, 'Shopping-Cart',
      {                                     // options are optional!
        maxDocuments: 99,                   // maximum number of line items in cart
        storageFull: function (col, doc) {  // function to handle maximum being exceeded
          col.remove({ _id: doc._id });
          alert('Shopping cart is full.');
        }
      });

    // create a helper to fetch the data
    UI.registerHelper("shoppingCartItems", function () {
      return shoppingCart.find();
    });

    // that's it. just use the collection normally and the observer
    // will keep it sync'd to browser storage. the data will be stored
    // back into the collection when returning to the app (depending,
    // of course, on availability of localStorage in the browser).

    shoppingCart.insert({ item: 'DMB-01', desc: 'Discover Meteor Book', quantity: 1 });
  });
}
<head>
  <title>Shopping Cart</title>
</head>

<body>
  {{> shoppingCart}}
</body>

<template name="shoppingCart">
  <table>
    <tr>
      <th>Item</th>
      <th>Description</th>
      <th>Quantity</th>
    </tr>
    {{#each shoppingCartItems}}
      <tr>
        <td>{{item}}</td>
        <td>{{desc}}</td>
        <td>{{quantity}}</td>
      </tr>
    {{/each}}
  </table>
</template>