In backbone.js view, how do i call another function from jquery $.each?

旧时模样 提交于 2019-12-12 05:49:08

问题


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

    }


来源:https://stackoverflow.com/questions/15138163/in-backbone-js-view-how-do-i-call-another-function-from-jquery-each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!