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

前端 未结 3 1956
旧巷少年郎
旧巷少年郎 2020-12-07 23:58

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 ge

相关标签:
3条回答
  • 2020-12-08 00:08

    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.

    0 讨论(0)
  • 2020-12-08 00:09

    The reset method (see 'reset') allows you to pass a JSON array to a collection. This is the equivalent of a PUT method, replacing the specified collection with the JSON hash.

    You can also use the add method to add to an existing collection, or pass the JSON hash into the constructor as you create a new collection.

    You'll have to do some basic cleaning up of your array to get it in an appropriate format, and then convert it to JSON

    0 讨论(0)
  • 2020-12-08 00:32

    I'm using PHP to grab a feed as JSON since it's on a different domain. I save those results to a JS variable, and then I just had success using this to get it into my Backbone collection...

    var feedCollection = new Backbone.Collection();
    feedCollection.set(myFeedJSON.nestedObject.nestedArrayIWant);
    
    0 讨论(0)
提交回复
热议问题