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

2019-09-18 17:27发布

问题:

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
}

回答1:

This should work.

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

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


回答2:

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);

    }