使用 Backbone js 读取 XML 并在视图中追加 [英] Read XML and append in view using Backbone js

查看:18
本文介绍了使用 Backbone js 读取 XML 并在视图中追加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Backbone 读取 XML 和追加视图.

XML 文件已被读取并成功附加到视图中.但我不知道如何在 Backbone 结构中进行处理(使用其模型).

XML 文件(读取asseturlwidthheight)

<资产><asset asseturl="img_1.png" width="100" height="150"></asset><asset asseturl="img_2.png" width="200" height="250"></asset><asset asseturl="img_3.png" width="300" height="350"></asset></资产></图书馆>

主干js代码

var Book = Backbone.Model.extend();var Books = Backbone.Collection.extend({型号:书,网址:文件.xml",解析:函数(数据){var $xml = $(data);返回 $xml.find('assets').map(function(){var bookTitle = $(this).find('asset').each(function(){var this_url = $(this).attr('asseturl');var this_width = $(this).attr('width');var this_height = $(this).attr('height');$('.character-list').append('<li><span class="asset char">'+'<img width="'+this_width+'" height="'+this_height+'" src="'+this_url+'">'+'</span></li>');});返回 {title: bookTitle};}).得到();},获取:功能(选项){选项 = 选项 ||{};options.dataType = "xml";返回 Backbone.Collection.prototype.fetch.call(this, options);}});var bookListView = Backbone.View.extend({初始化:函数(){this.listenTo(this.collection, "sync", this.render);},渲染:函数(){console.log(this.collection.toJSON());}});var bks = new Books();new bookListView({collection: bks});bks.fetch();

要附加的 HTML 代码

    尽管上述附加功能对我有用,但在 Backbone parse 函数中处理它并不是一个好习惯.

    解决方案

    不要把渲染逻辑放到集合的parse函数中.

    集合的作用是管理模型并与 API 同步.视图负责呈现.

    首先,让我们简化集合解析.在 Backbone 文档中,parse 应该只执行以下操作:><块引用>

    函数被传递给原始的 response 对象,并且应该返回要添加到集合中的模型属性数组.

    parse: function(response) {var $xml = $(响应);//这将返回一个对象数组返回 $xml.find('assets').children('asset').map(function() {var $asset = $(this);//返回原始的模型"属性返回 {资产网址:$asset.attr('asseturl'),宽度:$asset.attr('width'),高度:$asset.attr('height')};}).得到();},

    然后,为每个资产做一个简单的视图:

    var BookView = Backbone.View.extend({tagName: 'li',模板:_.template('<span class="asset char"><img width="<%= width %>" height="<%= height %>" src="<%= asseturl %>"></span>'),渲染:函数(){this.$el.html(this.template(this.model.toJSON()));返回这个;}});

    并且在列表视图中处理每个资产的渲染.

    var BookListView = Backbone.View.extend({初始化:函数(){this.childViews = [];this.listenTo(this.collection, "sync", this.render);},渲染:函数(){this.$el.empty();this.collection.each(this.renderBook, this);返回这个;},渲染书:函数(模型){var view = new BookView({模型:模型});this.childViews.push(view);this.$el.append(view.render().el);},});

    使用:

    var bks = new Books(),view = new BookListView({ el: $('.character-list'), collection: bks });视图渲染();bks.fetch();

    How to read XML and append in view with Backbone.

    XML file has been read and successfully appended in view. But i don't know how to approach in Backbone structure (Using its Model).

    XML file (read asseturl , width, height)

    <library>
        <assets>
            <asset asseturl="img_1.png" width="100" height="150"></asset>
            <asset asseturl="img_2.png" width="200" height="250"></asset>
            <asset asseturl="img_3.png" width="300" height="350"></asset>
        </assets>
    </library>
    

    Backbone js code

    var Book = Backbone.Model.extend();
    
    var Books = Backbone.Collection.extend({
        model: Book,
        url: "file.xml",
    
        parse: function (data) 
        {
            var $xml = $(data);
    
            return $xml.find('assets').map(function() 
            {      
                var bookTitle = $(this).find('asset').each(function(){
                var this_url = $(this).attr('asseturl');
                var this_width = $(this).attr('width');
                var this_height = $(this).attr('height');
    
                $('.character-list').append('<li><span class="asset char">'+
                '<img width="'+this_width+'" height="'+this_height+'" src="'+this_url+'">'+
                '</span></li>');
            });
            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();
    

    HTML code to append

    <ul class="character-list">
    </ul>
    

    Even-though the above append functionality works for me, it's not good practice to approach this in Backbone parse function.

    解决方案

    Don't put the rendering logic into the collection's parse function.

    The collection's role is to manage models and syncing with an API. It's the view's responsibility to render.

    First, let's simplify the collection parsing. From the Backbone documentation, parse should do the following only:

    The function is passed the raw response object, and should return the array of model attributes to be added to the collection.

    parse: function(response) {
        var $xml = $(response);
    
        // this will return an array of objects
        return $xml.find('assets').children('asset').map(function() {
            var $asset = $(this);
    
            // returns raw "model" attributes
            return {
                asseturl: $asset.attr('asseturl'),
                width: $asset.attr('width'),
                height: $asset.attr('height')
            };
    
        }).get();
    },
    

    Then, make a simple view for each asset:

    var BookView = Backbone.View.extend({
        tagName: 'li',
        template: _.template('<span class="asset char"><img width="<%= width %>" height="<%= height %>" src="<%= asseturl %>"></span>'),
        render: function() {
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        }
    });
    

    And it's in the list view that the rendering of each assets is handled.

    var BookListView = Backbone.View.extend({
        initialize: function() {
            this.childViews = [];
            this.listenTo(this.collection, "sync", this.render);
        },
        render: function() {
            this.$el.empty();
            this.collection.each(this.renderBook, this);
            return this;
        },
        renderBook: function(model) {
            var view = new BookView({ model: model });
            this.childViews.push(view);
            this.$el.append(view.render().el);
        },
    });
    

    To use it:

    var bks = new Books(),
        view = new BookListView({ el: $('.character-list'), collection: bks });
    view.render();
    bks.fetch();
    

    这篇关于使用 Backbone js 读取 XML 并在视图中追加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆