переменная окна, определенная в оконной функции, не видимой снаружи - PullRequest
0 голосов
/ 17 октября 2019

Я определил в качестве нового окна новый экземпляр объекта CanvasJS внутри оконной функции и назвал его диаграммой. Этот объект не виден в функции, управляющей движением ползунка. Задача состояла в том, чтобы перемещать горизонтальную линию на графике согласованно с движением ползунка. Здесь код

  1. ajax перехватывает обратную передачу и a. заполнить контейнер полученным HTML-кодом и сценариями b. Обработка функции для создания новой диаграммы

    $("#desktop_new_alarm_research").submit(function(e) {
    
    e.preventDefault(); // avoid to execute the actual submit of the form.
    
    var form = $(this);
    var url = ajax_url+'Login/getResearchResultsForNewPriceAlarms';
    
    $.ajax({
           type: "POST",
           url: url,
           data: form.serialize(), // serializes the form's elements.
           success: function(data)
           {
               var response = JSON.parse(data);             
    
            $('#research_results_container').html(response.rendered_page);
    
               if(response.state == 'success'){
    
                   if(response.galenic_made == false){
    
    
    
                        renderPriceGraphs(response.chart_name, response.min_price_usd, response.max_price_usd,response.factory_made,response.galenic_made,response.factory_made_max_min_graph_prices,response.factory_made_avg_graph_prices_stats);
                   }
    
                   if(response.galenic_made == true){
                        renderPriceGraphs(response.chart_name, response.min_price_usd,response.max_price_usd,response.factory_made,response.galenic_made,response.factory_made_max_min_graph_prices,response.factory_made_avg_graph_prices_stats,response.galenic_made_max_min_graph_prices,response.galenic_made_avg_graph_prices_stats);
                   }
               }
    
    
           }
         });
    
    
     });      
    
  2. на странице response.rendered_page также есть сценарий, который должен a. изменить текстовое поле со значением ползунка (это работает) б. изменить пороговую горизонтальную линию (это не работает)

    <script>
       // range slider code
       var slider = document.getElementById("myRange");
       var output = document.getElementById("demo");
       output.innerHTML = 
       parseFloat(slider.value).toPrecision(2);//.toPrecision(- 
      Math.floor(Math.log10(slider.value))+2);
    
    slider.oninput = function() {
    
        var min_slider_value = parseFloat(this.value); 
    
        output.innerHTML = min_slider_value.toPrecision(2);
        chart.axisY[0].stripLines[0].set("value",min_slider_value);
    
    //console.log("TEST "+response.state);
    };
    
    var slider1 = document.getElementById("myRange1");
    var output1 = document.getElementById("demo1");
    output1.innerHTML = 
       parseFloat(slider1.value).toPrecision(2);//.toPrecision(  - 
       Math.floor(Math.log10(slider.value))+2);
    
    
    slider1.oninput = function() {
    
        var max_slider_value = parseFloat(this.value);        
        output1.innerHTML = max_slider_value.toPrecision(2);
    
    
    };               
    

  3. в файле commonFunctions.js, загруженном на страницу перед обратной передачей функциидля создания графика, где относительная переменная диаграмма была определена как window.chart = new ...

     window.renderPriceGraphs = function(chart_name, min_price_usd, 
            max_price_usd, factory_made, galenic_made, 
                           factory_made_max_min_graph_prices, 
                           factory_made_avg_graph_prices_stats,
                           galenic_made_max_min_graph_prices = null,
                           galenic_made_avg_graph_prices_stats = null) {
    
    var max_line = max_price_usd*1.05;
    
    var min_line = min_price_usd*0.90;
    
    //alert("values "+max_price_usd+" "+min_price_usd);
    console.log("values ma and min"+max_line+" "+min_line);
    
    if(factory_made == true && galenic_made == true){
    
        //var chart = new CanvasJS.Chart(chart_name, {
        window.chart = new CanvasJS.Chart(chart_name, {
            animationEnabled: true,
            zoomEnabled:true,
            theme: "light2",
            title:{
                text: "Prices per unit of main active ingredients"
            },
            // subtitles: [{
            //   text: "High and Low Prices - 2016"
            // }],
            axisX: {
                valueFormatString: "MMM",
                intervalType: "month",
                interval: 1
            },
            axisY: {
                title: "Price (in USD)",
                prefix: "$",
                interval: 0.010,
                includeZero: false,
    
                stripLines:[
                    {                       
                        value: max_line,             
                        color:"#ff0000",
                        label: "Max threshold",
                        labelFontColor: "#ff0000",
                        showOnTop: true
                    },
                    {                       
                        value: min_line,             
                        color:"#00bc00",
                        label: "Min threshold",
                        labelFontColor: "#00bc00",
                        showOnTop: true
                    }
                ]
    
    
            },
            data: [
    
                    {
                        type: "rangeSplineArea",
                        showInLegend: true,
                        legendText: "Factory made max/min Prices",
                        xValueType: "dateTime",
                        xValueFormatString: "DD MMM",
                        yValueFormatString: "$#,##0.#######",
                        toolTipContent: "Factory made - {x}<br><b>Max:</b> {y[1]}<br><b>Min:</b> {y[0]}",
                        dataPoints: factory_made_max_min_graph_prices
                    },
                    {
                        type: "spline",
                        showInLegend: true,
                        legendText: "Average Factory Prices",
                        legendMarkerColor: "#dee0ec",
                        color: "#dee0ec",
                        lineColor: "#dee0ec",
                        markerSize: 5,
                        xValueFormatString: "DD MMMM",
                        yValueFormatString: "$#,##0.#####",
                        xValueType: "dateTime",
                        toolTipContent: "Factory made - <b>{x}</b> </br> Avg: {y}",
                        dataPoints: factory_made_avg_graph_prices_stats
                    },            
    
    
                    {
                        type: "rangeSplineArea",
                        showInLegend: true,
                        color: "#51bfc3",
                        fillOpacity: .3, 
                        legendText: "Galenic made max/min Prices",
                        xValueType: "dateTime",
                        xValueFormatString: "DD MMM",
                        yValueFormatString: "$#,##0.#######",
                        toolTipContent: "Galenic made - {x}<br><b>Max:</b> {y[1]}<br><b>Min:</b> {y[0]}",
                        dataPoints: galenic_made_max_min_graph_prices
                    },
                    {
                        type: "spline",
                        showInLegend: true,
                        legendText: "Average Galenic Prices",
                        legendMarkerColor: "#a6e6e8",
                        color: "#a6e6e8",
                        lineColor: "#a6e6e8",
                        markerSize: 5,
                        xValueFormatString: "DD MMMM",
                        yValueFormatString: "$#,##0.#####",
                        xValueType: "dateTime",
                        toolTipContent: "Galenic made - <b>{x}</b> </br> Avg: {y}",
                        dataPoints: galenic_made_avg_graph_prices_stats
                    },
    
            ]
        });
    }
    
    
    if(factory_made == true && galenic_made != true){
        var chart = new CanvasJS.Chart(chart_name, {
            animationEnabled: true,
            zoomEnabled:true,
            theme: "light2",
            title:{
                text: "Prices per unit of main active ingredients"
            },
            // subtitles: [{
            //   text: "High and Low Prices - 2016"
            // }],
            axisX: {
                valueFormatString: "MMM",
                intervalType: "month",
                interval: 1
            },
            axisY: {
                title: "Price (in USD)",
                prefix: "$",
                interval: 0.010,
                includeZero: false,
                stripLines:[
                    {                       
                        value: max_line,             
                        color:"#ff0000",
                        label: "Max threshold",
                        labelFontColor: "#ff0000",
                        showOnTop: true
                    },
                    {                       
                        value: min_line,             
                        color:"#00bc00",
                        label: "Min threshold",
                        labelFontColor: "#4b4b4b",
                        showOnTop: true
                    }
                ]
    
            },
            data: [
    
                    {
                        type: "rangeSplineArea",
                        showInLegend: true,
                        legendText: "Factory made max/min Prices",
                        xValueType: "dateTime",
                        xValueFormatString: "DD MMM",
                        yValueFormatString: "$#,##0.#######",
                        toolTipContent: "Factory made - {x}<br><b>Max:</b> {y[1]}<br><b>Min:</b> {y[0]}",
                        dataPoints: factory_made_max_min_graph_prices
                    },
                    {
                        type: "spline",
                        showInLegend: true,
                        legendText: "Average Factory Prices",
                        legendMarkerColor: "#dee0ec",
                        color: "#dee0ec",
                        lineColor: "#dee0ec",
                        markerSize: 5,
                        xValueFormatString: "DD MMMM",
                        yValueFormatString: "$#,##0.#####",
                        xValueType: "dateTime",
                        toolTipContent: "Factory made - <b>{x}</b> </br> Avg: {y}",
                        dataPoints: factory_made_avg_graph_prices_stats
                    },   
            ]
        });
    }
    
    chart.render();
    
    };
    

Глядя на консоль, я получаю ошибку

VM596:12 Uncaught ReferenceError: chart is not defined
at HTMLInputElement.slider.oninput (<anonymous>:12:9)

как будто объект диаграммы не был виден в глобальной области видимости. Есть идеи?

1 Ответ

0 голосов
/ 17 октября 2019

Проверьте переменную factory_made: true или false. может быть, это false и оно не удовлетворяет никакому условию if, а переменная chart остается undefined

...