BackboneJS with XML ajax

后端 未结 1 683
余生分开走
余生分开走 2020-12-14 11:56

this is a two part question from a JS newbie.

So, I was trying to create a backbone application using requireJS by following Thomas Davis\'s tutorial.

相关标签:
1条回答
  • 2020-12-14 12:31
    1. You can override the default parse function to provide XML support. It should return the data transformed into JSON http://backbonejs.org/#Collection-parse

    2. Bind the render to a reset event instead of refresh for Backbone<1.0 or to a sync event for Backbone>=1.0

    It could look like this

    var Book = Backbone.Model.extend();
    
    var Books = Backbone.Collection.extend({
        model: Book,
        url: "books.xml",
    
        parse: function (data) {
            var $xml = $(data);
    
            return $xml.find('book').map(function () {
                var bookTitle = $(this).find('name').text();
                return {title: bookTitle};
            }).get();
        },
    
        fetch: function (options) {
            options = options || {};
            options.dataType = "xml";
            return Backbone.Collection.prototype.fetch.call(this, options);
        }
    });
    
    var bookListView = Backbone.View.extend({
        initialize: function () {
            this.listenTo(this.collection, "sync", this.render);
        },
    
        render: function () {
            console.log(this.collection.toJSON());
        }
    });
    
    var bks = new Books();
    new bookListView({collection: bks});
    bks.fetch();
    

    And a demo http://jsfiddle.net/ULK7q/73/

    0 讨论(0)
提交回复
热议问题