2013-02-11 84 views
1

我想在我的JS文件中声明一个全局变量,并且我想在同一个类的不同函数中使用该变量。 我宣布在初始化部分变量在Handlebar中声明公共变量JS

 initialize: function() {    
        this.regionid=""; 
    } 

      selectItems: function() 
       { 

       this.regionid="10"; 
       this.Regions.url = this.Regions.url() + '?requesttype=1'; 
       this.Regions.fetch({ success: this.renderRegion }); 


    } 

    renderRegion: function() { 
      var ddlRegionClass = this.Regions.toJSON(); 
      $(this.el).find('[id=cboRegion] option').remove();   
      $.each(ddlRegionClass.LOCATIONS_Regions, function (j, cc1) { 
       var data = 'data='+cc1.AreaCode_2; 
        var selected = '';     
        if(cc1.AreaCode_3==this.regionid) 
          selected="selected";     

       $('[id=cboRegion]').append('<option value="' + cc1.AreaCode_3 + '" ' + data + selected + ' >' + cc1.Area_Name + '</option>'); 
      }) 
     }, 

虽然我检查在

if(cc1.AreaCode_3==this.regionid) 

值我没有得到的值,则显示“未定义”

回答

2
this.regionid=""; 
initialize: function() { 
//some code 
} 

我认为你必须像这样声明..然后它会工作..你可以在任何函数中为变量赋值。

+0

非常感谢,它工作! – 2013-02-11 04:58:45

0

this$.each的回调内部不会引用view(或js文件所包含的对象)。

在初始化,您可以用this结合renderRegion

initialize: function() { 
    this.regionid = ""; 
    _.bindAll(this, "renderRegion"); 
} 

和内部renderRegion

renderRegion: function() { 
    // before doing $.each store 'this' reference 
    var _this = this; 

    // and inside the callback use if(cc1.AreaCode_3 == _this.regionid) 
} 

它应该工作。