1

How can I send JSON to the initialization of a model? I am trying to make the model dynamic based on a form:

v = new ModelObject($('#form-id').serializeJSON());

But this stores the form data as just one attribute and an object. I'd like to use the JSON attributes as the model attributes.

2 Answers 2

2

You'll need to get a better serializer. I built one called Syphon, specifically to do this with backbone:

https://github.com/derickbailey/backbone.syphon


var data = Backbone.Syphon.serialize(someViewWithAForm);

var model = new Backbone.Model(data);

Or Ben Alman's serializeObject jQuery extension: http://benalman.com/projects/jquery-misc-plugins/#serializeobject

Sign up to request clarification or add additional context in comments.

Comments

1

You can populate the model with form data by using this code:

var data = {};
$.each(this.$("#formId").serializeArray(), function(index, val) {
  data[val.name] = val.value;
});

then call save or init the moduel with the data.

var demo = new My.Dynamic.Model(data);

or

var demo = new My.Dynamic.Model();
demo.save(data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.