我有一个类似于下面所示的backbone.js模型。
Filters = Backbone.Model.extend({
defaults : {
title: [ ["title1", "easy"], ["title2", "hard"] ]
}
});
我正在尝试向第一级数组添加元素,以便模型变为:
Filters = Backbone.Model.extend({
defaults : {
title: [ ["title1", "easy"], ["title2", "hard"], ["title3", "medium"] ]
}
});
我现在的代码是:
function setFilters() {
var options = {};
for (var facet in facets) {
for (var facetKey in facets[facet]) {
if (!filterExists(facetKey)) {
options[facetKey] = new Array(new Array(facets[facet][facetKey], "equals"));
}
else {
(filters[facetKey]).push(new Array(facets[facet][facetKey], "equals"));
}
}
}
filters.set(options);
}
函数 filterExists 只检查模型中是否存在键“title”。当我运行它时,它说过滤器[facetKey]是未定义的。但这不是我需要将元素推入的第一级数组吗?
答案 0 :(得分:8)
您可以使用.get()
和.set()
函数访问模型属性,也可以直接通过.attributes
属性访问:
http://documentcloud.github.com/backbone/#Model-attributes
var filters = new Filters();
filters.attributes.facetKey.push( [...] );
OR
filters.set('facetKey', ( filters.get('facetKey') || []).concat([...]));
无论如何,这是你的转换函数,它可能有效,也可能无效:
function setFilters() {
for (var facet in facets) {
for (var facetKey in facets[facet]) {
var f = [ facets[facet][facetKey], "equals" ];
if( filterExists(facetKey)) {
// OR: if( filters.attributes[ facetKey ]){
filters.attributes[ facetKey ].push( f );
}else{
filters.attributes[ facetKey ] = [ f ];
}
}
}
// trigger change event for all attributes
filters.set( filters.attributes );
}
加成:
(filters.attributes[ facetKey ] = filters.attributes[ facetKey ] || [] ).push(f);