Reputation: 73
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.
Upvotes: 1
Views: 1426
Reputation: 174
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);
Upvotes: 1
Reputation: 72888
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
Upvotes: 2