Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Allow model.schema to be a function that returns the schema object

  • Loading branch information...
commit 72ce855b302a13107285b313666e0f65934e8ec2 1 parent 05cc2b0
@powmedia authored
Showing with 35 additions and 3 deletions.
  1. +2 −0  README.md
  2. +15 −3 src/backbone-forms.js
  3. +18 −0 test/form.js
View
2  README.md
@@ -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"/>
#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:
- [Text](#editor-text)
View
18 src/backbone-forms.js
@@ -329,13 +329,25 @@
* 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)
*/
- initialize: function(options) {
- this.schema = options.schema || (options.model ? options.model.schema : {}),
+ initialize: function(options) {
+ //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.data = options.data;
this.fieldsToRender = options.fields || _.keys(this.schema);
this.fieldsets = options.fieldsets;
-
+
//Stores all Field views
this.fields = {};
},
View
18 test/form.js
@@ -30,6 +30,24 @@ test("'schema' option - If not present, the 'schema' attribute on the model is u
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() {
var post = new Post();
Please sign in to comment.
Something went wrong with that request. Please try again.