3

reportManager.save("/EditInitiatives.svc/SaveGridData");调用方法时出现错误

<script type='text/javascript'>
$(function () {
    $('#saveReport, #save-report-bottom').click(function () {
        $.blockUI({ message: '<h4><img src="/Images/busy.gif" /> Saving your changes.<br/>This operation might impact several reports at once.<br/>Please be patient.</h4>' });
        uiController.disableSaveButton();
        reportManager.save("/EditInitiatives.svc/SaveGridData");
    });

    var reportManager = function () {
        var tableData = JSON.stringify(handsontable.getData());
        var input = JSON.stringify({ "input": tableData });
        alert("Data" +  input); 

        save = function(saveUrl) { 
            alert("save" + saveUrl);

            $.ajax({
                url: saveUrl,
                type: 'POST',
                dataType: 'json',
                data: input, //returns all cells' data
                contentType: 'application/json; charset=utf-8',
                success: function(res) {
                    if (res.result === 'ok') {
                        console.text('Data saved');
                    }                        
                    $.unblockUI();                            
                }, 
                error: function (xhr) {
                    alert(xhr.responseText);
                }                       
            });
        }
    };
}
</script>
4

2 回答 2

3

您无法访问它,因为它save是一个全局变量而不是reportManager.

它之所以是全局的,是因为您缺少变量前面的 var 。这将其放入全局命名空间。它不会神奇地连接到函数的块范围。您需要使用 OO 方法才能使其正常工作。一些基本的想法是

function Report() {
     var x = 1;
    this.save = function () {
        alert("First: " + x);   
    }
}

var report = new Report();
report.save();


function report_2() {
     var x = 1;
    return {
        save : function () {
            alert("Second: " + x);   
        }
    }
}

var report2 = report_2();
report2.save();


var report_3 = (function () {
     var x = 1;

    var returnObj = {};
    returnObj.save = function () {
            alert("Third: " + x);   
    }

    return returnObj;


    //return {
    //    save  :  function() {
    //        alert("Third: " + x);   
    //    }
    //}
})();

report_3.save();

例子的小提琴:http: //jsfiddle.net/5Zhsq/

于 2013-05-15T17:18:45.763 回答
0

您已经声明了save没有var关键字的函数;因此它将在全局范围内声明,而不是作为reportManager.

即使您将var关键字放在savefunction 之前,也无法从reportManagerfunction外部访问它scope。要将它暴露给公众,你需要export它。这是一个简单的模式:

 var reportManager = (function (self) {

      function save(saveUrl) { ... } //this function is not public yet

      self.save = save; //we are exporting the save function here
      return self; //now we are returning an object with save function

 })(reportManager || {});


 reportManager.save("your-param-here"); //Now use your function the way you want
于 2013-05-15T17:25:16.447 回答