我正在使用 backbone 来填充下拉列表。 API 的更改导致数据(选项标签)返回不需要的数据,例如“Option Foo - 00011222”而不是“Option Foo”
我打算使用正则表达式,这样我就只能显示“-”之前的第一个字符
在呈现给 View 之前清理集合中数据的最佳方法是什么。
应该在 View 上还是在集合上完成
最佳答案
如果附加数据可以安全丢弃,可以使用Model.parse修改您收到的数据:
parse model.parse(response, options)
parse is called whenever a model's data is returned by the server, in fetch, and save. The function is passed the raw response object, and should return the attributes hash to be set on the model.
例如,如果你想替换一个label
字段:
var data = [
{label: 'Option Foo - 00011222'},
{label: 'Option Foo2 - 00011222'}
];
var M = Backbone.Model.extend({
parse: function(data) {
data.label = data.label.replace(M.regexp, '');
return data;
}
}, {
regexp: /\s*-.*$/
});
var C = Backbone.Collection.extend({
model: M
});
var c = new C(data, {parse: true});
console.log(c.pluck('label'));
关于javascript - Backbone js - 在传递给 View 之前使用集合(模型)上的正则表达式清理数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16080059/