如何将参数传递给Collection解析? Backbone.js的

时间:2015-07-22 16:45:48

标签: javascript backbone.js

如何通过parse / fetch函数传递参数? 我想在较低的Initialize-part中传递变量 VARIABLE_PARAMETER

否则我必须写三个大部分相同的集合。

谢谢你的帮助。

app.js

//--------------
// Collections
//--------------

    DiagnoseApp.Collections.Param1_itemS = Backbone.Collection.extend({
        model: DiagnoseApp.Models.Param1_item,
        url: 'TestInterface.xml',
        parse: function (data) { 
            var parsed = [];

            $(data).find(/*VARIABLE_PARAMETER*/).find('PARAMETER').each(function (index) {
                var v_number = $(this).attr('Number');
                var v_Desc_D = $(this).attr('Desc_D');
                parsed.push({ data_type: v_data_type, number: v_number, Desc_D: v_Desc_D});
            });

            return parsed;
        },

        fetch: function (options) { 
            options = options || {};
            options.dataType = "xml";
            return Backbone.Collection.prototype.fetch.call(this, options);
        }
    });

这是我初始化应用的方式:

    //--------------
    // Initialize
    //--------------

    var VARIABLE_PARAMETER = "OFFLINE";

    var offline_Collection = new DiagnoseApp.Collections.Param1_itemS();
    var offline_Collection_View = new DiagnoseApp.Views.Param1_itemS({collection: offline_Collection});


    //VARIABLE_PARAMETER has to be passed here in fetch I guess ??

     offline_Collection.fetch({
        success: function() {
              console.log("JSON file load was successful", offline_Collection);

              offline_Collection_View.render();
          },
        error: function(){
           console.log('There was some error in loading and processing the JSON file');
        }

    });

2 个答案:

答案 0 :(得分:1)

fetch方法接受option参数:http://backbonejs.org/#Collection-fetch parse方法也接受option参数:http://backbonejs.org/#Collection-parse 这些对象实际上是相同的。所以你可以写:

parse: function (data, options) { 
        var parsed = [];

        $(data).find(options.variableParameter).find('PARAMETER').each(function (index) {
            var v_number = $(this).attr('Number');
            var v_Desc_D = $(this).attr('Desc_D');
            parsed.push({ data_type: v_data_type, number: v_number, Desc_D: v_Desc_D});
        });

        return parsed;
    },

答案 1 :(得分:0)

不确定我理解你的问题,但是如果你想传递一个参数"从fetchparse,如果该参数值对于给定的集合没有变化,您只需将其存储在集合中即可。您可以将参数作为fetch中的附加属性传递给options

fetch: function (options) { 
    options = options || {};
    options.dataType = "xml";
    this.variableParameter = options.variableParameter;
    return Backbone.Collection.prototype.fetch.call(this, options);
},

然后只需检索它

parse: function (data) { 
    // do something useful with this.variableParameter
    // ...
}