2015-06-10 137 views
0

我有JSON对象;让我们称之为模型;它有2个类型数组的属性。该模型还有一个函数“hasAnyFilterSelected”,用于检查是否有任何数组属性被填充。我在UI上有下拉列表的搜索按钮。当用户点击搜索按钮时,会出现以下步骤:将函数添加到JSON对象

1>将所选值从下拉列表中推送到模型的数组 属性中。

2> model.hasAnyFilterSelected()检查数组中是否有值,在调试器中我看到模型中填充了值。

3>如果是,则刷新通过执行datasource.read()

4>剑道格称为“getFilters”方法,该方法在调试器我看到模型中填充值再次返回模式,剑术网格。

5>然后不知何故 hasAnyFilterSelected()被再次调用,这一次模型阵列属性是不确定的。它看起来像剑道试图再次序列化模型,这次模型有不同的实例,但我不知道。

$(function() { 

    var model = { 
     selectedTaxYears: [], 
     selectedStates: [], 

     hasAnyFilterSelected: function() { 
      return !(this.selectedTaxYears.length == 0 &&     
       this.selectedStates.length == 0) 
     } 
    };  

    $_btnSearch.click(function() { 
     pushFilters(); 
     if (model.hasAnyFilterSelected()) // this returns true when array is populated. In debugger I could see its populated 
     { 
      $(gridID).data("kendoGrid").dataSource.read(); 
      // fails at above line when dataSource reads 
      // it calls getFilters method as expected, I see model is populated. 
      // then it calls hasAnyFilterSelected() function again, (don’t know why) and at this time selectedTaxYears & selectedStates is undefined, so it fails 
      // In debugger I DO NOT see model is populated. So looks like different instance of model 

      $(gridID).data('kendoGrid').refresh(); 
     } 
    }); 


    function pushFilters() { 
     model.selectedTaxYears = $_taxYears.val(); 
     model.selectedStates = $_stateProvience.val();  
    }  

    function getFilters() { 
      return model; 
     } 

    var dataSource = $_grid.data("kendoGrid").dataSource; 
    dataSource.transport.options.read.data = getFilters; 
}) 

我想知道为什么会发生这种情况?我是否正确定义了JSON函数?那是首选方法?

回答

0

如果我理解正确,您的值将被保留,但是您的函数正在被覆盖或被忽略? (也许当被地方复制,正如你指出。)不知道,如果这第一步的工作,但有可能尝试用原型函数写它作为一个更明确的类:

var model_class = function() { 
    this.selectedTaxYears = []; 
    this.selectedStates = []; 
} 
model_class.prototype = { 
    hasAnyFilterSelected: function() { 
     return !(this.selectedTaxYears.length == 0 &&     
      this.selectedStates.length == 0) 
} 
var model = new model_class(); 

如果被覆盖,另一种方法是在singleton库的其他地方或者在'window'范围内定义该函数,然后使用'.apply'调用它:

if (model_hasAnyFilterSelected.apply(this)) { 
    //// etc 
}