• Stars
    star
    367
  • Rank 116,257 (Top 3 %)
  • Language
    JavaScript
  • Created over 13 years ago
  • Updated about 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

store and restore your model's state

Backbone.Memento

Memento push and pop for Backbone.js models and collections structures.

A view may offer some editing capabilities that directly modify a structure (model or collection), directly. If you want to cancel the changes after they have already been applied to the structure, you will have to make a round trip to the back-end server or other origin of the structures's data to do so.

With the memento pattern and the Backbone.Memento plugin, you do not need to make any round trips.

Getting Started

It's easy to get up and running. You only need to have Backbone (including underscore.js - a requirement for Backbone) in your page before including the backbone.memento plugin.

Prerequisites

  • Backbone.js v0.5.3, v0.9.0, or higher

This plugin is built and tested against Backbone v0.9.0 but should run against most versions of Backbone, as it only uses functionality built into the Backbone structures. Namely, it uses the set and unset methods of models and reset and remove of collections.

Get The Memento Plugin

Download the backbone.memento.js file from this github repository and copy it into your javascripts folder. Add the needed <script> tag to bring the plugin into any page that wishes to use it. Be sure to include the modelbinding file after the backbone.js file.

Setup A Model/Collection For Mementoing

Your models must make use of the Backbone.Memento object, directly. This can easily be done in multiple ways

Extend The Memento

You can tell a model instance to extend a memento instance. This will provide all of the memento methods directly on the model.

SomeModel = Backbone.Model.extend({
  initialize: function(){
    var memento = new Backbone.Memento(this);
    _.extend(this, memento);
  }
});

Cherry-Picking Methods

You can also configure a model by instantiating the memento with your model's initializer and then providing access to the methods as needed, or by using the methods internally.

SomeModel = Backbone.Model.extend({
  initialize: function(){
    this.memento = new Backbone.Memento(this);
    this.restart = this.memento.restart;
  },

  someAppMethod: function(){
    this.memento.set();
  },

  moreAppMethod: function(){
    this.memento.store();
    // ... do stuff here

    // ... then restart it if needed
    this.memento.restore();
  }
});

This gives you more control over where the memento methods can be used.

Memento with Collections

Memento has been recently upgraded to support collections and saving state of the models under the hood. This will greatly assist with filtering collections temporarily.

Note the use of reset intead of set.

SomeCollection = Backbone.Collection.extend({
  initialize: function() {
    _.extend(this, new Backbone.Memento(this));
  }
});

var someCollection = new SomeCollection();
someCollection.reset({something: "whatever"});
someCollection.store();
someCollection.reset({something: "a change"});
someCollection.restore();

someCollection.at(0).get("something"); //=> "whatever"

Memento Methods

There are several methods provided by Backbone.Memento, to allow you more control over how the memento object works, and when.

memento.store

This method creates a copy of your structure's current state, as a memento, and stores it in a stack (first in, last out).

memento.restore

This method takes the previously stored state, and restores your structure to this state. You can call this as many times as you have called store. Calling this method more times than you have called store will result in a no-operation and your structure will not be changed.

memento.restart (formerly reset)

This method effectively rolls your structure back to the first store point, no matter how many times it has been stored in the memento.

(reset was deprecated since it has a naming conflict with Backbone.Collections.prototype.reset.)

Configuration

There is only one item of configuration for Backbone.Memento at the moment:

Ignore Model Attributes

There are some scenarios where it may cause issues to have all attributes restored from a previous state, for a model. In this case, you can ignore specific attributes for the model.

Ignore For The Model Instance

You can configure the memento to ignore the attributes when instantiating the memento:

SomeModel = Backbone.Model.extend({
  initialize: function(){
    _.extend(this, new Backbone.Memento(this, {
      ignore: ["something", "another", "whatever", "..."]
    });
  },

  // ...
});

var someModel = new SomeModel();
someModel.set({something: "whatever"});
someModel.store();
someModel.set({something: "a change"});
someModel.restore();

someModel.get("something"); //=> "a change"

Ignore For This Restore Only

Alternatively, you can override the pre-configured ignored attributes by passing an ignore array into the restore method:

SomeModel = Backbone.Model.extend({
  initialize: function(){
    this.memento = new Backbone.Memento(this);
  },

  // ...
});

var someModel = new SomeModel();
someModel.set({something: "whatever"});
someModel.store();
someModel.set({something: "a change"});
someModel.restore({ignore: ["something"]});

someModel.get("something"); //=> "a change"

Note that passing an ignore array into the restore method will override the pre-configured ignore list.

Examples

With this in place, you can push your model's state onto the memento stack by calling store, and pop the previously stored state back into the model (destroying the current state in the process) by calling restore.

myModel = new SomeModel();
myModel.set({foo: "bar"});

myModel.store();

myModel.set({foo: "a change"});

myModel.restore();

myModel.get("foo"); // => "bar"

Set And Unset Attributes

Backbone.Memento will set and unset attributes, when poping from the memento stack. For example, if you add an attribute after storing your models state, and then later restore back to the previous state, the attribute that you added will be unset. The unset attribute will have it's change event fired, as well.

myModel = new SomeModel();
myModel.set({foo: "stuff"});

myModel.store();

myModel.set({bar: "a new attribute"});

myModel.bind("change:bar", function(model, value){
  alert('bar was changed to: ' + val);
}

myModel.restore(); // => causes an alert box to say "bar was changed to undefined"

myModel.get("bar"); // => undefined, as the attribute does not exist

Release Notes

v0.4.1a

  • No code changes were made. This release is for library upgrades only, for testing purposes
    • Updated Backbone to v0.9.0
    • Updated Underscore to v1.3.1
    • Updated jQuery to v1.7.1

v0.4.1

  • Fixed global scope leak for a variable

v0.4.0

v0.3.0

  • changed the public memento API to support collections
  • updated documentation to reflect changes

v0.2.0

  • changed the public memento API and how a model is connected to the memento
  • changed the name of the 'clear' method to 'restart', to prevent hijacking the model's clear method
  • updated the documentation to include better examples and more detail

v0.1.4

  • ability to ignore model attributes - they won't be stored or restored

v0.1.3

  • Fixed a small bug with rolling back more times than had been saved

v0.1.2

  • Added ability to restart a model, moving back to the beginning of the memento stack
  • Fixed a few bugs in the removing of old attributes, related to global variables, etc
  • Code cleanup and switching to a standard object constructor function instead of return an object literal

v0.1 and v0.1.1

  • Initial releases with a few minor bug fixes

Legal Mumbo Jumbo (MIT License)

Copyright (c) 2011 Derick Bailey, Muted Solutions, LLC

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

backbone.modelbinding

awesome model binding for Backbone.js
JavaScript
700
star
2

mustbe

Authorization plumbing for NodeJS/ExpressJS/ConnectJS apps
JavaScript
320
star
3

Albacore

Dolphin-Safe Rake Tasks For .NET Systems
Ruby
240
star
4

jasmine.async

Make Jasmine's asynchronous testing suck less.
JavaScript
136
star
5

backbone.picky

selectable entities as mixins for Backbone.Model and Backbone.Collection
JavaScript
129
star
6

rabbus

A micro-service bus with built-in messaging patterns, for NodeJS and RabbitMQ
JavaScript
116
star
7

express-sub-app-demo

Demonstrates the ability to mount multiple Express apps into a single Express host app
JavaScript
111
star
8

solid-javascript

SOLID JavaScript In A Wobbly World (Wide Web)
JavaScript
70
star
9

nanit

Node Application Initializers
JavaScript
56
star
10

migroose

MongoDB database / data-structure migrations, for MongooseJS models and schemas
JavaScript
55
star
11

appcontroller

An example Application Controller implementation for C# WinForms applications
C#
35
star
12

emberclonemail

A sample application written with EmberJS
Ruby
32
star
13

backbone.compute

Computed fields for Backbone.Model
JavaScript
31
star
14

presentations-and-training

Material used for presentations and training classes
C#
26
star
15

backbone.fwd

forward events from one backbone object, through another
JavaScript
20
star
16

bowie

An experiment in beautiful models with ES6 elegance
JavaScript
19
star
17

hands-on-backbone

The sample code to go along with the "Hands-on Backbone.js" screencast series from PragProg.com
JavaScript
18
star
18

iam

Simple authentication plumbing and middleware for Node/Express apps
JavaScript
15
star
19

bada55-node-dev

How to build your own #BADA55 NodeJS development environment
JavaScript
14
star
20

UnitOfWork

A C# UnitOfWork Implementation For NHibernate. Supports WinForms and ASP.NET.
C#
12
star
21

epa

simple environment configuration for nodejs apps, using json files
JavaScript
11
star
22

speccy

simple javascript specification pattern implementation for nodejs / browserify
JavaScript
9
star
23

appcontroller.cf

Application Controller example code for the .NET Compact Framework
C#
8
star
24

jquery-to-backbone-marionette

code demo for my "jQuery To Backbone + Marionette" talk
JavaScript
8
star
25

boebotjs

Make Your Bot GO! With JavaScript!
JavaScript
8
star
26

Security

A small, role based security module for .NET apps
C#
7
star
27

vimbacore

a playground to try out c# coding in vim and figure out what albacore's csc task needs
Ruby
7
star
28

docker4js

Docker for JavaScript Developers - 2 day, hands-on training course from Derick Bailey
JavaScript
5
star
29

migroose-cli

command line tooling for mongrate, the mongodb/mongoosejs migration framework
JavaScript
5
star
30

5-tips-to-improve-js-with-es6

presentation given at Crater Remote Conf, Feb 10th, 2016
JavaScript
5
star
31

backbone-sinatra-boilerplate

My boilerplate cruft for working with Backbone.js in a Sinatra-backed app
JavaScript
5
star
32

MyFirstMVCSeleniumTest

How To Get Started With Selenium Core And ASP.NET MVC
JavaScript
4
star
33

classyobjects

A class-y inheritance example for JavaScript
JavaScript
3
star
34

backboneplugins

website for backboneplugins.com
CSS
3
star
35

ninject.rhinomocks.cf

Automocking container for RhinoMocks, running on Compact Framework
C#
3
star
36

5-stages-of-developer-grief

Presented at SpaceCityJS 2015
3
star
37

vimfiles.osx

my osx .vim folder and .vimrc
Vim Script
3
star
38

5-stages-of-entrepreneurial-grief

presentation for PrarieDevCon 2015
3
star
39

ninject.rhinomocks

Automocking container for RhinoMocks
C#
3
star
40

growing-express-architecture

Growing Express.js Architecture - a talk given at JSRemoteConf on Jan 15, 2016.
3
star
41

node-oracledb-cpu-leak

app to demonstrate node-oracledb cpu leak / spike
JavaScript
2
star
42

gitup

Automate the git update dance
Shell
2
star
43

execubot.js

A sample WebTask.io project: Read and execute code from a gist, post it in slack channel.
JavaScript
2
star
44

backbone.presentation

My slide deck for a Backbone.js presentation
JavaScript
2
star
45

cheesewiz

Correctly package localized resource files in .NET Comptact Framework .cab deployment projects
C#
2
star
46

jsfuncalc

An exercise in creating a functional javascript calculator
Ruby
2
star
47

ocarina

Simplified API for Oracle, built on top of official orabledb library
JavaScript
2
star
48

apologypro

apology.pro: because you're an amateur
JavaScript
2
star
49

boxing

terrible dropbox api and express middleware
JavaScript
2
star
50

mutedsolutions

website for my company
CSS
2
star
51

alt-tekpub

An open rewrite of Tekpub using Node, MongoDB and other buzzwords
JavaScript
1
star
52

objects

1
star
53

vimfiles.windows

my vim files and _vimrc for windows
Vim Script
1
star
54

derickbailey.github.com

My Github Homepage!
1
star
55

rabbus-sequence

process messages in sequential order with Rabbus and RabbitMQ
JavaScript
1
star
56

puzzleblocks

a command line game inspired by the Nintaii game that I play on my Droid
Ruby
1
star
57

traffic-limiter

Limit the number of tasks being run, based on task key/type
JavaScript
1
star
58

express-depot

mount Express sub-apps and middleware from a directory listing
JavaScript
1
star
59

react-todo-example

a basic example of organizing code in a basic react/redux app
JavaScript
1
star
60

wacotechlunch

Waco Tech Lunch
1
star
61

dotfiles

my dotfiles
Vim Script
1
star
62

node-jasmine-async

Making Jasmine's async suck less (for Jasmine v1.3)
JavaScript
1
star