Skip to content

Instantly share code, notes, and snippets.

@philfreo
Created October 13, 2012 17:40
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save philfreo/3885499 to your computer and use it in GitHub Desktop.
Save philfreo/3885499 to your computer and use it in GitHub Desktop.
Backbone-Forms InlineNestedModel
/* vim: set tabstop=2 shiftwidth=2 softtabstop=2: */
define([
'backbone',
'backbone-forms'
],
function(Backbone) {
var Form = Backbone.Form,
editors = Form.editors;
// we don't want our nested form to have a (nested) <form> tag
// (currently bbf includes form tags: https://github.com/powmedia/backbone-forms/issues/8)
// aside from being strange html to have nested form tags, it causes submission-upon-enter
Form.setTemplates({
nestedForm: '<div class="bbf-nested-form">{{fieldsets}}</div>'
});
editors.List.InlineNestedModel = editors.List.NestedModel.extend({
events: {},
/**
* @param {Object} options
*/
initialize: function(options) {
editors.Base.prototype.initialize.call(this, options);
// Reverse the effect of the "feature" of pressing enter adding new item
// https://github.com/powmedia/backbone-forms/commit/6201a6f44984087b71c216dd637b280dab9b757d
delete this.options.item.events['keydown input[type=text]'];
var schema = this.schema;
if (!schema.model) throw 'Missing required option "schema.model"';
this.nestedSchema = schema.model.prototype.schema;
if (_.isFunction(this.nestedSchema)) this.nestedSchema = this.nestedSchema();
var list = options.list;
list.on('add', this.onUserAdd, this);
},
/**
* Render the list item representation
*/
render: function() {
var self = this;
this.$el.html(this.getFormEl());
setTimeout(function() {
self.trigger('readyToAdd');
}, 0);
return this;
},
getFormEl: function() {
var schema = this.schema,
value = this.getValue();
// when adding a new item, need to instantiate a new empty model
// TODO is this the best place for this?
if (!value) { value = new schema.model(); }
this.form = new Form({
/*
schema: this.nestedSchema,
data: this.value
*/
template: 'nestedForm',
model: value
});
return this.form.render().el;
},
getValue: function() {
if (this.form) {
this.value = this.form.getValue();
//console.log('nested form value', this.value);
// see https://github.com/powmedia/backbone-forms/issues/81
}
return this.value;
},
onUserAdd: function() {
this.form.$('input, textarea, select').first().focus();
}
});
return Backbone;
});
@m-vdb
Copy link

m-vdb commented Dec 4, 2012

@philfreo I'm really interested in the idea of your editor, but i'd like to use it with objects instead of NestedModels. Do you think a simple workaround is possible ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment