Skip to content

Instantly share code, notes, and snippets.

@ssafejava
Last active December 17, 2015 02:48
Show Gist options
  • Save ssafejava/5537970 to your computer and use it in GitHub Desktop.
Save ssafejava/5537970 to your computer and use it in GitHub Desktop.
Backbone.LayoutManager compatibility plugin for Backbone.Forms. Works with Backbone v1.0 and LayoutManager v0.9.
define([
'jquery',
'lodash',
'backbone',
'backbone-forms'
], function($, _, Backbone, BackboneForms) {
'use strict';
/**
* This class contains overrides & patches for the Backbone.Form class.
*
* Some of these changes were necessitated for compatibility with Backbone.layoutManager. Others
* make my life easier.
*
* We are still using layoutmanager, we just have to modify some information to get them to play nice.
*/
// Cache overriden functions
var formInitialize = Backbone.Form.prototype.initialize;
var formRender = Backbone.Form.prototype.render;
_.extend(Backbone.Form.prototype, {
/**
* On View construction, set up a few compatibility layers between LM and Backbone.Form.
* @param {Object} options Options passed to this form.
*/
initialize: function(options) {
// Backbone.Form expects fieldsets in the options hash. This allows us
// to define fieldsets right on the View.
if (this.fieldsets) this.options.fieldsets = _.extend(this.options.fieldsets || {}, this.fieldsets);
// Prevents subviews from inheriting any subclass (bad design, Backbone.Form)
this.constructor = Backbone.Form;
// Backbone.Form expects template data in `this.templateData`.
if (_.isFunction(this.serialize)){
var serialize = this.serialize;
this.serialize = function(){
this.templateData = serialize.apply(this, arguments);
return this.templateData;
};
}
// Backbone.Form looks for 'template' in options.template.
if (this.template){
this.options.template = this.template;
}
// This calls Backbone.Form's initialize.
// Backbone.Form doesn't actually look at `this.options`, it just expects them to be passed in.
// So pass them in.
return formInitialize.call(this, this.options);
},
/**
* Proxy Backbone.Forms rendering.
*/
renderTemplate: function() {
// If we have a layoutmanager template location in a string, find the template & use it.
// XXX this may break if you grab async templates. Use grunt-jst if you can or
// rewrite this to work async.
if (_.isString(this.template)){
this.template = this.options.fetchTemplate(this.options.prefix + this.template);
}
// Call Backbone.Form's render method.
formRender.apply(this, arguments);
return this;
}
});
// Turn off LayoutManager's management of these superclasses.
_.extend(Backbone.Form.Fieldset.prototype, { manage: false });
_.extend(Backbone.Form.Field.prototype, { manage: false });
_.extend(Backbone.Form.Editor.prototype, { manage: false });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment