Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Backbone Model using received JSON data

I know how to create a new backbone model. But how I can create a backbone model with the data which is received from a web service?

For example, you are receiving a JSON data from a webservice. I want to use this JSON as backbone model. How I can do that?

Thanks.

like image 234
jaks Avatar asked Jun 06 '12 12:06

jaks


2 Answers


MyModel = Backbone.Model.extend({});

var data = { /* some data you got from the ajax call */};

var m = new MyModel(data);

Or if you don't need a specific type of model, you can just use a generic Backbone.Model


var data = { /* some data you got from the ajax call */};

var m = new Backbone.Model(data);
like image 130
Derick Bailey Avatar answered Oct 13 '22 02:10

Derick Bailey


It's not clear if you're trying to create a model definition or a model instance.
Either way, if your service is returning a json object, somehing like should work:

var data = {/*received data*/};

// for a new model definition
var newModelDefinition = Backbone.Model.extend(data);
// that you can instantiate later on:
var model1 = new newModelDefinition(),
    model2 = new newModelDefinition(someData);

// for a new model instance
var newModelInstance = new Backbone.Model(data);
like image 32
gion_13 Avatar answered Oct 13 '22 03:10

gion_13