backbone.js将文本文件加载到集合中

时间:2013-02-12 11:18:08

标签: parsing backbone.js text-files loading

这是我第一次使用框架进行开发并坚持第一步。

我正在将Flex应用程序转换为Javascript应用程序并使用骨干作为框架。

我必须加载一个名称值格式的文本文件。

<!doctype html>
<html>
<head>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.10/backbone-min.js'></script>
<script>
var ResourceBundleCollection = Backbone.Collection.extend({
url:'ResourceBundle.txt',
});
var resourceBundleCollection = new ResourceBundleCollection();
resourceBundleCollection.fetch();
</script>
</head>
<body>
</body>
</html>

ResourceBundle.txt包含以下格式的内容

location_icon=../../abc/test.png
right_nav_arrow_image=assets/images/arrow.png
right_nav_arrow_image_visible=true

抛出以下错误 没有良好的形式

我可以使用JQuery轻松加载文本文件并解析它

$.ajax({
type : "GET",
url : "ResourceBundle.txt",
datatype : "script",
success : resourceXMLLoaded
});

并使用以下代码解析它

var lines = txt.split("\n");
for(var i=0;i<lines.length;i++) {
if(lines[i].length > 5) {
var _arr = lines[i].split("=");
resourceBundleObj[$.trim(_arr[0])] = $.trim(_arr[1]);
}
}

请告知如何在backbone.js中获得相同的结果

2 个答案:

答案 0 :(得分:5)

如果你必须使用纯文本来支持这一点,你可以覆盖Backbone.Collection.parse来实现你所需要的。

除此之外,您可能还需要创建一个ResourceBundleModel来托管ResourceBundleCollection中的每个项目。

您可以在此处查看演示:http://jsfiddle.net/dashk/66nkF/

模型代码&amp;收集在这里:

// Define a Backbone.Model that host each ResourceBundle
var ResourceBundleModel = Backbone.Model.extend({
    defaults: function() {
        return {
            name: null,
            value: null
        };
    }
});

// Define a collection of ResourceBundleModels.
var ResourceBundleCollection = Backbone.Collection.extend({
    // Each collection should know what Model it works with, though
    // not mandated, I guess this is best practice.
    model: ResourceBundleModel,

    // Replace this with your URL - This is just so we can demo
    // this in JSFiddle.
    url: '/echo/html/',

    parse: function(resp) {
        // Once AJAX is completed, Backbone will call this function
        // as a part of 'reset' to get a list of models based on
        // XHR response.
        var data = [];
        var lines = resp.split("\n");

        // I am just reusing your parsing logic here. :)
        for (var i=0; i<lines.length; i++) {
            if (lines[i].length > 5) {
                var _arr = lines[i].split("=");

                // Instead of putting this into collection directly,
                // we will create new ResourceBundleModel to contain
                // the data.
                data.push(new ResourceBundleModel({
                    name: $.trim(_arr[0]),
                    value: $.trim(_arr[1])
                }));
            }    
        }

        // Now, you've an array of ResourceBundleModel. This set of
        // data will be used to construct ResourceBundleCollection.
        return data;
    },

    // Override .sync so we can demo the feature on JSFiddle
    sync: function(method, model, options) {
        // When you do a .fetch, method is 'read'
        if (method === 'read') {
            var me = this;

            // Make an XHR request to get data
            // Replace this code with your own code
            Backbone.ajax({
                url: this.url,
                method: 'POST',
                data: {
                    // Feed mock data into JSFiddle's mock XHR response
                    html: $('#mockData').text()
                },
                success: function(resp) {
                    options.success(me, resp, options);
                },
                error: function() {
                    if (options.error) {
                        options.error();
                    }
                }
            });
        }
        else {
            // Call the default sync method for other sync method
            Backbone.Collection.prototype.sync.apply(this, arguments);
        }
    }
});

Backbone旨在通过JSON本地使用RESTful API。然而,它是一个足够灵活的库,可以满足您的需求,并提供足够的自定义。

答案 1 :(得分:2)

默认情况下,Backbone中的集合只接受JSON格式的集合。 因此,您需要将输入转换为JSON格式:

[{"name": "name", "value": "value},
 {"name": "name", "value": "value}, ...
]

当然,您可以覆盖默认行为: Overriding backbone's parse function