How can we introduce hierarchies of deep models in Backbone.js

I see that there are methods that allow you to have deep models in Backbone, but what about hierarchical collections of one model?

An obvious example is a category tree. Thus, we can have a category model that has several properties: "name", "type", "color", whatever.

Instead of having parent identifiers for relational db types, we use js, so we want the data to be represented as json.

Can the basic framework be used to support (presumably by increasing collections) data structures containing instances of the same model in the tree (for example, models and submodules are instances of the same model)?

+6
source share
1 answer

Take a look at Backbone-Relational or supermodel.js .

These projects provide better forms of nesting than the default implementation.

We simply embed Backbone models, for example:

var MyModel = Backbone.Model.extend({}); var MySubModel = Backbone.Model.extend({}); var model = new MyModel({submodel: new MySubModel({color: 'blue'})}); 

And we override the toJSON methods:

 // nested models! Might just override the internal representation of this... _.extend(Backbone.Model.prototype, { // Version of toJSON that traverses nested models toJSON: function() { var obj = _.clone(this.attributes); _.each(_.keys(obj), function(key) { if(!_.isUndefined(obj[key]) && !_.isNull(obj[key]) && _.isFunction(obj[key].toJSON)) { obj[key] = obj[key].toJSON(); } }); return obj; } }); _.extend(Backbone.Collection.prototype, { // Version of toJSON that traverses nested models toJSON: function() { return this.map(function(model){ return model.toJSON(); }); } }); 

That way, JSON views look right when we insert models. You will need to pay attention to the parse method on your model, although - when you return your JSON from the server, you will have to create all the submodels and collections there so that everything works correctly.

+8
source

Source: https://habr.com/ru/post/918601/


All Articles