Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

javascript - How to build a Collection/Model from nested JSON with Backbone.js

I'm relativly new to Backbone.js

I have a JSON like the picture shows ! I saw some Answers in relation with Backbone-relational, but still dont get the point!

How can i convert this JSON to Backbone.js Collections/Models??

I update with a code but it dont work like expected! i can't see an model when i do :

My Structure is :

[0] : is a collection of models

[clefs] + ... + [Rest] : are collection of models

(clefs) => [0] + ... + [9] : are Models(title contains a string, path too)

Thanks a lot!!

EDIT(10.01.12) :

My Solution :

window.initModel = Backbone.Model.extend({
  defaults: {
    "title": "",
    "path": ""
  }
});
window.CustomCollection = Backbone.Collection.extend({
  model: initModel
});
window.Init = Backbone.Model.extend({
  url : function(){
    return  "/api/data.json"      
  },

  parse: function(response) {

    clefs = new CustomCollection();
    clefs.add(response.clefs);        
    this.set({clefs: clefs});

    .....

    rests = new CustomCollection();
    rests.add(response.rests);        
    this.set({rests: rests});
} 
});

this helped me out too!

Nested Array

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm at work, so I cannot give you a fully coded answer, but the gist is, you can do the following in your top level models to achieve a nested model hierarchy:

var AmericasNextTopModel = Backbone.Models.extend({
    initialize: function(){

        this.set({
             clefs: new ClefCollection(this.get('clefs')),
             accidentals: new AccidentalCollection(this.get('accidentals')),
             notes: new NoteCollection(this.get('notes')),
             rests: new RestCollection(this.get('rests'))
        });
    }
});

I do not use backbone-relational so I cannot give you an answer regarding that.

Are you making an online sheet music viewer/editor? :D Cool I'd love to see it when you're done.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...