2016-11-29 57 views
0

這是我有的控制器,我想將currencyCheck移動到一個模型或單獨的utility.js文件,我可以在控制器中加載,但問題是全局變量。我不知道如何使用全局變量將函數移動到單獨的js文件中。有沒有辦法在UI5中聲明全局變量?如何在控制器中訪問模型聲明中的變量?

sap.ui.define([ 
    'jquery.sap.global', 
    'sap/ui/core/mvc/Controller', 
    'sap/ui/model/json/JSONModel', 
    'sap/ui/model/Filter', 
    'sap/ui/model/FilterOperator', 
    'sap/m/MessageToast' 
], 

function(jQuery, Controller, JSONModel, Filter, FilterOperator, MessageToast) { 
    "use strict"; 

    var price; 
    var mainController = Controller.extend("pricingTool.controller.Main", { 


     //define global variables 
     globalEnv: function() { 
      nsnButton = this.byId("nsnButton"); 
      price = this.byId("price"); 
     }, 

     onInit: function(oEvent) { 

      //moving this code to Component.js 
      //define named/default model(s) 
      var inputModel = new JSONModel("model/inputs.json"); 
      var productsModel = new JSONModel("model/products.json"); 

      //set model(s) to current xml view 
      this.getView().setModel(inputModel, "inputModel"); 
      this.getView().setModel(productsModel); 

      //default application settings 
      //unload global variables 
      this.globalEnv(); 
     }, 

     currencyCheck: function(oEvent) { 
      var inputVal = oEvent.getParameters().value; 
      var detailId = oEvent.getParameters().id; 
      var id = detailId.replace(/\__xmlview0--\b/, ""); 
      var currencyCode; 
      var inputArr = inputVal.split(""); 

      currencyCode = inputArr[0] + inputArr[1] + inputArr[2]; 

      if (id === "price") { 

       if (inputArr[0].match(/^[\d$]+$/) || currencyCode === 'USD') { 
        price.setValueState("None"); 
       } else price.setValueState("Error"); 


      } else if (id === "unitPrice") { 
       console.log(inputVal); 
       if (inputArr[0].match(/^[\d$]+$/) || currencyCode === 'USD') { 
        unitPrice.setValueState("None"); 
       } else unitPrice.setValueState("Error"); 
      } 


     }, 

     onNsnChange: function() { 
      //enable "Search" button if input has an entry 
      searchQuery = nsnSearchInput.getValue(); 

      if (searchQuery === "") { 
       nsnButton.setEnabled(false); 
      } else { 
       nsnSearchInput.setValueState("None"); 
       nsnButton.setEnabled(true); 
      } 
     }, 


    }); 

    return mainController; 
}); 
+0

不要使用這樣的全局變量!你爲什麼需要它們? – matbtt

回答

2

如何不使用全局變量?你可以使你的變量本地化,並將它們作爲參數傳遞給任何其他方法,即使在其他類中也是如此。

在你utility.js定義傳輸方法如下:

currencyCheck: function (oEvent, price) { 
    ... 
    // the code from the original function 
    ... 
} 

然後,你可以做你的MainController如下:

currencyCheck: function (oEvent) { 
    var oPrice = this.byId("price"); 
    Utility.currencyCheck(oEvent, oPrice); 
} 

當然,你必須在一開始導入實用類你的控制器文件。

相關問題