Sha256: 5e820c504a60312bbee22b9d2ac7bf0af679923116505cc036faf0d71b83d0ad

Contents?: true

Size: 1.82 KB

Versions: 6

Compression:

Stored size: 1.82 KB

Contents

(function(Backbone, _) {
  var NestedAttributesModel      = Backbone.NestedAttributesModel,
      NestedAttributesModelProto = NestedAttributesModel.prototype

  function UndoableState(model) {
    this.model = model

    model.on('nested:change', this.change, this)
    model.on('change',        this.change, this)
    model.on('sync',          this.save,   this)
  }

  _.extend(UndoableState.prototype, Backbone.Events, {
    change: function () {
      this.changed = true
    },

    save: function () {
      this.updateAttributes()

      this.model.trigger('state:store')
    },

    undo: function () {
      this.attributesToUnset().each(function (attribute) {
        this.model.unset(attribute)
      }, this)

      this.model.set(this.attributes)

      this.updateAttributes()

      this.model.trigger('state:restore')
    },

    attributesToUnset: function () {
      var previousAttributes = _(this.attributes || {}).keys()

      return _(this.model.attributes).chain().keys().select(function (attribute) {
        return !_(previousAttributes).include(attribute)
      })
    },

    updateAttributes: function () {
      this.attributes = this.model.toJSON({ withDeleted: true })
      this.changed = false
    }
  })

  Backbone.UndoableModel = NestedAttributesModel.extend({
    initialize: function () {
      NestedAttributesModelProto.initialize.apply(this, arguments)

      this.undoable()
    },

    undoable: function () {
      this.saveState()
    },

    undo: function () {
      this.undoableState().undo()
    },

    hasChangedSinceSync: function () {
      return this.undoableState().changed === true
    },

    saveState: function () {
      this.undoableState().save()
    },

    undoableState: function () {
      return this._undoableState = this._undoableState || new UndoableState(this)
    }
  })
})(Backbone, _);

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
backbone-nested-attributes-0.5.0 app/assets/javascripts/backbone-nested-attributes/undoable.js
backbone-nested-attributes-0.4.4 app/assets/javascripts/backbone-nested-attributes/undoable.js
backbone-nested-attributes-0.4.3 app/assets/javascripts/backbone-nested-attributes/undoable.js
backbone-nested-attributes-0.4.2 app/assets/javascripts/backbone-nested-attributes/undoable.js
backbone-nested-attributes-0.4.1 app/assets/javascripts/backbone-nested-attributes/undoable.js
backbone-nested-attributes-0.4.0 app/assets/javascripts/backbone-nested-attributes/undoable.js