Skip to content

Instantly share code, notes, and snippets.

@bgrins
Created April 26, 2013 16:16
Show Gist options
  • Save bgrins/5468477 to your computer and use it in GitHub Desktop.
Save bgrins/5468477 to your computer and use it in GitHub Desktop.
backbone-helpers: extend Backbone natives with some convenience methods.
// 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