In backbone.js view, how do i call another functio

2019-09-18 17:11发布

In my backbone.js view i have a function that has the code below. I would usually call this function using this.addLayerToList(), but since it's in the $.each this. is not what I want. Can anyone help here? How would I call my function addLayerToList from the $.each?

initLayerList: function(){
   $.each(baseLayers, function() {
       this.addLayerToList(this);
   });
},

addLayerToList : function() {
     //...some code here
}

2条回答
Viruses.
2楼-- · 2019-09-18 17:29

Since you are using Backbone, Underscore.js is also included and available to you. You can use Underscore's each method, which lets you pass this into the context of your loop:

 initLayerList: function(){
      _.each(baseLayers, function(layer){
        this.addLayerToList(layer);
      }, this);

    },
    addLayerToList : function() {
         //...some code here
    }

If baselyayers is a Backbone collection, you can simplify the code a little further:

 initLayerList: function(){
      baseLayers.each(function(layer){
        this.addLayerToList(layer);
      }, this);

    }
查看更多
姐就是有狂的资本
3楼-- · 2019-09-18 17:42

This should work.

initLayerList: function(){
   var that = this;
   $.each(baseLayers, function(idx, layer) {
       that.addLayerToList(layer);
   });
},

addLayerToList : function() {
     //...some code here
}
查看更多
登录 后发表回答