Skip to content

Commit

Permalink
Allow model.schema to be a function that returns the schema object
Browse files Browse the repository at this point in the history
  • Loading branch information
powmedia committed Mar 16, 2012
1 parent 05cc2b0 commit 72ce855
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -145,6 +145,8 @@ If a form has a model attached to it, the initial values are taken from the mode
<a name="schema-definition"/> <a name="schema-definition"/>
#Schema definition #Schema definition


The schema defined on your model can be the schema object itself, or a function that returns a schema object. This can be useful if you're referencing variables that haven't been initialized yet.

The following default editors are included: The following default editors are included:


- [Text](#editor-text) - [Text](#editor-text)
Expand Down
18 changes: 15 additions & 3 deletions src/backbone-forms.js
Expand Up @@ -329,13 +329,25 @@
* data {Array} : Pass this when not using a model. Use getValue() to get out value * data {Array} : Pass this when not using a model. Use getValue() to get out value
* fields {Array} : Keys of fields to include in the form, in display order (default: all fields) * fields {Array} : Keys of fields to include in the form, in display order (default: all fields)
*/ */
initialize: function(options) { initialize: function(options) {
this.schema = options.schema || (options.model ? options.model.schema : {}), //Get the schema
this.schema = (function() {
if (options.schema) return options.schema;

var model = options.model;
if (!model) throw new Error('Could not find schema');

if (_.isFunction(model.schema)) return model.schema();

return model.schema;
})();

//Handle other options
this.model = options.model; this.model = options.model;
this.data = options.data; this.data = options.data;
this.fieldsToRender = options.fields || _.keys(this.schema); this.fieldsToRender = options.fields || _.keys(this.schema);
this.fieldsets = options.fieldsets; this.fieldsets = options.fieldsets;

//Stores all Field views //Stores all Field views
this.fields = {}; this.fields = {};
}, },
Expand Down
18 changes: 18 additions & 0 deletions test/form.js
Expand Up @@ -30,6 +30,24 @@ test("'schema' option - If not present, the 'schema' attribute on the model is u
equal($('textarea', form.el).length, 1); equal($('textarea', form.el).length, 1);
}); });


test('The schema on the model can be a function', function() {
var post = new Post,
_schema = post.schema;

post.schema = function() {
return _schema;
}

var form = new Form({
model: post
}).render();



//Stored correct schema object
equal(form.schema, _schema);
});

test("'model' option - Populates the form", function() { test("'model' option - Populates the form", function() {
var post = new Post(); var post = new Post();


Expand Down

0 comments on commit 72ce855

Please sign in to comment.