繁体   English   中英

将变量从Backbone.js路由器初始化函数传递到另一个路由器函数的forEach语句

[英]pass variable from Backbone.js router initialize function to the forEach statement of another router function

请在下面查看更新的代码...

我正在尝试使用forEach语句通过另一个集合的属性来过滤一个集合。 我如何编写此代码以维护对forEach语句中的变量“ this.neighborhoodsCollection”的引用。 这可能不是问题, 问题。 换句话说,我想我该如何将变量“ this.neighborhoodsCollection”传递到我的forEach语句中。 这是我要采取的步骤:

我将获取StoryStory和NeighborhoodsCollection的结果传递给路由器:

$(document).ready(function() {
        var neighborhoodsCollection = new NeighborhoodsCollection();
        neighborhoodsCollection.fetch({
            success: function(){
                var storyCollection = new StoryCollection();
                storyCollection.fetch({
                    success: function () {
                    var app = new AppRouter(neighborhoodsCollection, storyCollection);
                    Backbone.history.start();
                    }
                });
            }
        });
    });

然后我将传入的参数设置为局部变量...

initialize: function(neighborhoodsCollection, storyCollection){
    this.neighborhoodsCollection = neighborhoodsCollection;
    this.storyCollection = storyCollection;

}

在路由器的另一个功能中,我针对“邻居”集合中的每个“邻居”属性检查当前storyCollection中的邻居阵列,如果存在匹配项,则将“邻居”集合对象添加到我的Leaflet地图中。

load_story:function (id) {
        //get Stories model object by id
        this.story = this.storyCollection.get(id);

var storyNeighborhoods = this.story.attributes.neighborhoods;

    storyNeighborhoods.forEach(function(neighborhood){

     var hood = this.neighborhoodsCollection.attributes;
     var nabe = [];
     var nabeGeo = [];


     for(var i = 0; i < _.size(hood); i++){
         nabe.push(this.neighborhoodsCollection.attributes[i].properties.neighborhood);

         nabeGeo.push(this.neighborhoodsCollection.attributes[i]);

         var filterNabe = $.inArray(neighborhood, nabe);

         if(filterNabe > -1){
            L.geoJson(nabeGeo).addTo(map);
         }else{
            console.log('not found')
         }
     }
 });
}

UPDATE

@Quince的答案使我走上了正确的轨道,使用了采摘和交集解脱帮手。 现在,我有一个包含每个匹配的邻域字符串的数组。 然后,我尝试使用该字符串对集合进行获取。 这是我的收藏的数据结构:

Object { cid: "c1", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object, _pending: false }

这是我集合中唯一对象的结构:

[{ "id": "Greenpoint", "type": "Feature", "properties": { "neighborhood": "Greenpoint", "boroughCode": "3", "borough": "Brooklyn" ... }]

但是,我无法在此集合上成功执行get(id)。 也许与需要根据集合中的每个对象创建模型有关,或者类似的事情?

供参考,以下是基于@Quince示例的相关代码:

  var neighborhoodsCollection = this.neighborhoodsCollection;

var neighborhoodsCollectionObjects = this.neighborhoodsCollection.attributes;

var neighborhoodsCollectionProperties = _.pluck(neighborhoodsCollectionObjects, 'properties');

var neighborhoodsCollectionArray = _.pluck(neighborhoodsCollectionProperties, 'neighborhood');

var storyCollectionNeighborhoods = this.story.attributes.neighborhoods;

var neighborhoodIntersection = _.intersection(storyCollectionNeighborhoods, neighborhoodsCollectionArray);

NeighborhoodIntersection的值是一个包含单个字符串“ Greenpoint”的数组

neighborhoodIntersection.forEach(function(neighborhood){
    neighborhoodsCollection.get(neighborhood);
});

我希望我理解正确,您想浏览每个故事,并且如果它的某个邻域与主要邻域集合中的某个邻域相匹配,那么您想获取对其的引用吗?

解决该问题的方法是,在将故事的邻域集合中的ID与主要邻域集合中的ID进行比较时,使用下划线相交功能。 然后使用此列表从主要邻域集合中获取实际参考。 以下是我的意思的示例( 或代码笔,这样您就可以在控制台中看到已获得引用

//setup of models and collections 
var NeighbourHoodModel = Backbone.Model.extend({
  defaults:{
    name: null
  }
});

var StoryModel = Backbone.Model.extend({
  defaults:{
    neighbourhoods:null
  }
});
var NeighborhoodsCollection = Backbone.Collection.extend({
  model: NeighbourHoodModel
});
var StoryCollection = Backbone.Collection.extend({
  model: StoryModel
})

var neighbourHoods = new NeighborhoodsCollection([
  { id:1,name: "neighbourhood-1"},
  { id:2,name: "neighbourhood-2"},
  { id:3,name: "neighbourhood-3"},
  { id:4,name: "neighbourhood-4"}
]);

var stories = new StoryCollection([
  { id:1, neighbourhoods: new NeighborhoodsCollection([
      { id:1,name: "neighbourhood-1"},
      { id:2,name: "neighbourhood-2"}
     ]),
  },
  { id:2, neighbourhoods: new NeighborhoodsCollection([
      { id:1,name: "neighbourhood-1"},
      { id:2,name: "neighbourhood-2"}
     ]),
  }
]);

(function(neighbourHoods,stories){
  var _matchedNeighbourhoodIds = [];
  //grab an array (usign pluck) of all the nighboorhood ids
  //do this here so don;t have to do it on every loop
  var neighbourhoodIds = neighbourHoods.pluck("id");

  stories.forEach(function(story){

   //for each story grab an array (using pluck) of all the stories neighborhoods
   //perform an intersection of the two arrays (returning an array of id's that appear in both lists)
    //slice that array
    //for each element add it to the _matchNeighbourhoods in at a sorted index (this is so that we don't end with duplicates in the array)
    _.intersection(story.get("neighbourhoods").pluck("id"),neighbourhoodIds).slice(0).forEach(function(neighbourhoodId){
      _matchedNeighbourhoodIds[_.sortedIndex(_matchedNeighbourhoodIds,neighbourhoodId)] = neighbourhoodId;
    });
  });


  _matchedNeighbourhoodIds.forEach(function(matchedNeighbourHoodId){
         console.log(neighbourHoods.get(matchedNeighbourHoodId));
});

})(neighbourHoods,stories);

在完成此操作后,我刚刚看到的一个问题是_.sortedIndex,尽管该数组仅包含matchedNeighbourhoods的唯一ID,但是在添加已经匹配的邻域时,仍需要花一些时间来使这些值正确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM