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

て烟熏妆下的殇ゞ 提交于 2019-11-28 04:25:47
Daryl Teo

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.

djlumley

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

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!