Backbone.js 如何在主干中使用数组作为id
在主干网中,我有一个来自web服务器的json结构,如下所示(注意,我将只接收一组文档,因此不用于restful服务) {'stations':[station1,station2],'geo':[lat1,lng1,lat2,lng2….},其中'stations'数组只有两个数字表示公交车站编号,而'geo'表示两个车站之间的中间地理位置点。通常在应用程序中,我可以在任何数组[station1,station2]或[station2,station1]中获取stations数组,然后我使用此stations数组作为唯一id来获取“geo”数组-中间地理位置点 例如,{'stations':[3830638304],'geo':[53.21579073715244,-2.8958864745734445,53.26019,-2.94229700000000532]},这意味着我有两个编号为38306和38304的站,以及4个长度数组'geo',代表2个地理点Backbone.js 如何在主干中使用数组作为id,backbone.js,Backbone.js,在主干网中,我有一个来自web服务器的json结构,如下所示(注意,我将只接收一组文档,因此不用于restful服务) {'stations':[station1,station2],'geo':[lat1,lng1,lat2,lng2….},其中'stations'数组只有两个数字表示公交车站编号,而'geo'表示两个车站之间的中间地理位置点。通常在应用程序中,我可以在任何数组[station1,station2]或[station2,station1]中获取stations数组,然后我使用此
window.stanoxPoints = Backbone.Model.extend({
defaults:{
"stations":new Array(),
"points":new Array()
}
});
window.stanoxPointsCollection = Backbone.Collection.extend({
model: stanoxPoints,
url:"http://localhost:8080/geo",
});
var stanoxCollection = new stanoxPointsCollection();
stanoxCollection.fetch({
success:function(collection,response){
console.log('fetch the data success');
collection.each(function(data){
console.log(data.get('stations')+" "+data.get('points'));
})
},
error:function(collection, response){
}
})
所以我用上面的方法简单地设计了模型,并使用集合获取数据,但是当我想要查询数据时,出现了一些错误
stanoxCollection.get([38201,38202]) //undefined
我的问题是,如果我只使用“station”数组来获取“geo”数组,我如何将其作为主干模型中的id或索引,并且无论数组“stations”的顺序是什么,e.x[station1,station2]或[station2,station1]它都可以获取geo点数组,只有当站点数组顺序颠倒时,geo阵列的顺序也颠倒了
现在我已经试着将其命名为“stations”,因为原始id是[3820138202],所以
console.log('fetch get by id',stanoxCollection.get([3820138202]).get('points');//作品
console.log('fetch get by id',stanoxCollection.get([3820238201]);//不适用于id为的反向数组
有办法解决吗 服务器是返回一个json数组还是像您所展示的那样只返回一个json对象?您的
成功
回调是否被击中?它是否将任何内容记录到控制台?似乎您正试图在只有单个对象的情况下获取集合。它不是单个对象,服务器将返回一个json数组,fetch接收到成功,并且console.log(data.get('stations')+“”+data.get('points');对我有用。所以我有点困惑为什么我使用collection.at(0).get('stations')时collection不起作用,说'get'是未定义的我希望stanoxCollection.get([3820138202])
不起作用,因为get
接受模型引用或模型id。你在做stanoxCollection.at(0).get('stations'))
在成功
回调中还是之后?如果没有,则您可能会看到错误。是的,stanoxCollection.at(0).get('stations')在成功回调后工作,但是我应该如何使用'station'数组来获取'geo'数组,'station'作为id?其中({'stations':[3820138202]});不适用于meCan您只需添加一个新函数,执行您需要的特殊get
逻辑,因为您似乎需要对象可能有多个键。我还认为,id
可以转换为字符串,而不是存储为数组。