Created
April 26, 2013 16:16
-
-
Save bgrins/5468477 to your computer and use it in GitHub Desktop.
backbone-helpers: extend Backbone natives with some convenience methods.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// backbone-helpers: extend Backbone natives with some convenience methods | |
// Implemented by overriding the extend function to modify the options passed into the original extend | |
// Adds the following methods: | |
// Model.isDirty() -> check if a model has changed since the last sync with the server | |
// Collection.getChangedSinceLastSave() -> return all the models that return true on isDirty() | |
// Collection.saveAllChanged() -> save all the models returned by getChangedSinceLastSave() | |
(function (extend) { | |
Backbone.Model.extend = function (opts) { | |
opts.cleanAttributes = {}; | |
opts.clean = function () { | |
this.cleanAttributes = _.clone(this.attributes); | |
}; | |
opts.isDirty = function () { | |
return !_.isEqual(this.cleanAttributes, this.attributes); | |
}; | |
// Wrap initialize function to prevent overriding the user defined initialize | |
var initialize = opts.initialize; | |
opts.initialize = function () { | |
if (initialize) { | |
initialize.apply(this, arguments); | |
} | |
this.on("sync", function () { | |
this.clean(); | |
}); | |
this.clean(); | |
}; | |
return extend.apply(this, arguments); | |
}; | |
})(Backbone.Model.extend); | |
(function (extend) { | |
Backbone.Collection.extend = function (opts) { | |
opts.getChangedSinceLastSave = function () { | |
return this.filter(function (model) { | |
return model.isDirty() || model.isNew(); | |
}); | |
}; | |
opts.saveAllChanged = function () { | |
_.each(this.getChangedSinceLastSave(), function (model) { | |
model.save(); | |
}); | |
}; | |
return extend.apply(this, arguments); | |
}; | |
})(Backbone.Collection.extend); | |
Backbone.LocalStorageView = Backbone.View.extend({ | |
localStoragePrefix: false, | |
localStorage: false, | |
storage: function (key, val) { | |
if (typeof window.localStorage !== 'undefined') { | |
this.localStorage = window.localStorage; | |
} | |
if (!this.localStoragePrefix) { | |
return; | |
} | |
var localStorage = this.localStorage || {}; | |
var isSetting = typeof val !== "undefined"; | |
if (isSetting) { | |
localStorage[this.localStoragePrefix + "." + key] = val; | |
} | |
else { | |
return localStorage[this.localStoragePrefix + "." + key]; | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment