Skip to content

Instantly share code, notes, and snippets.

@A
Last active August 29, 2015 14:11
Show Gist options
  • Select an option

  • Save A/66a782b7c6774d5d15be to your computer and use it in GitHub Desktop.

Select an option

Save A/66a782b7c6774d5d15be to your computer and use it in GitHub Desktop.
Backbone's plugin design
'use strict';
// Dependencies
var {Model} = require('backbone');
module.exports = class PluginAdapter extends Model {
constructor(parent, options) {
this.name = options.name;
super(this.parse(parent));
parent.use('save:before', this.save.bind(this));
parent.on('change:'+this.name, parent => this.set(this.parse(parent)));
}
// logic to parse plugin data from parent model
parse(parent) {
return parent.get(this.name);
}
// dump data
dump() {
return this.toJSON()
}
// on save parent
save(parent) {
parent.set(this.name + '_attributes', this.dump());
parent.unset(this.name, { silent: true });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment