«Ожидается объект Javascript» при работе с Google Visualization API

Привет всем, поэтому я работаю над созданием небольшого класса, который поможет мне работать с API визуализации Google. Вы можете увидеть, как это работает здесь...

http://code.google.com/apis/visualization/documentation/gallery/annotatedtimeline.html

Вот реализация Google.

google.load('visualization', '1', {'packages':['annotatedtimeline']});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('date', 'Date');
        data.addColumn('number', 'Sold Pencils');
        data.addColumn('string', 'title1');
        data.addColumn('string', 'text1');
        data.addColumn('number', 'Sold Pens');
        data.addColumn('string', 'title2');
        data.addColumn('string', 'text2');
        data.addRows([
          [new Date(2008, 1 ,1), 30000, undefined, undefined, 40645, undefined, undefined],
          [new Date(2008, 1 ,2), 14045, undefined, undefined, 20374, undefined, undefined],
          [new Date(2008, 1 ,3), 55022, undefined, undefined, 50766, undefined, undefined],
          [new Date(2008, 1 ,4), 75284, undefined, undefined, 14334, 'Out of Stock','Ran out of stock on pens at 4pm'],
          [new Date(2008, 1 ,5), 41476, 'Bought Pens','Bought 200k pens', 66467, undefined, undefined],
          [new Date(2008, 1 ,6), 33322, undefined, undefined, 39463, undefined, undefined]
        ]);

        var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
        chart.draw(data, {displayAnnotations: true});

Вот класс, который я сделал, с которым у меня проблемы. Класс делает добавление данных на график немного проще и лучше для того, что я пытаюсь сделать. По сути, вместо того, чтобы создавать столбцы с кучей неопределенных значений, класс делает это за вас, и вам не нужно отслеживать местоположение/значение каждого столбца.

 function GraphManager(dataTable)
 {
     this.graphData = new Array();
     this.dataTable = dataTable;

     this.titleFinder = new Object(); // used to keep track of the indices

     this.dataTable.addColumn('date', 'Date');

     this.addSet = function(title)
     {

         var setCount = (this.dataTable.getNumberOfColumns() -1) / 3; //used for the column name
         var place = this.dataTable.getNumberOfColumns(); 

         this.titleFinder[title] = place; //the title of the column and its location

         this.dataTable.addColumn('number', title);
         this.dataTable.addColumn('string', 'title' + setCount);
         this.dataTable.addColumn('string', 'text' + setCount); 

     }

     this.addPoint = function(title, date, number)
     {
         //this function finds the location of the category
         //and inserts a column with data at the location


         var place = titleFinder[title]; //get the location

         var column = new Array(dataTable.getNumberOfColumns()); 
         column[0] = date;
         column[place] = number;

         for (var i = 0;i<place; i++)
         {
            column[i] = undefined; 
         }

         for (var i = place + 1; i<dataTable.getNumberOfColumns(); i++)
         {
             column[i] = undefined;
         }

         var next = this.graphData.length;
         this.graphData[next] = column;
         data.addRows(graphData);

     }


 }

И затем этот код можно использовать, чтобы сделать то же самое с меньшим количеством кода. function printGraph() { var data = new google.visualization.DataTable();

     var gm = new GraphManager(data);
     var title = "testcategory";


     gm.addSet(title);
     gm.addPoint(title, new Date[2010, 5, 10], 100);
     gm.addPoint(title, new Date[2010, 6, 10], 200);


     var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
     chart.draw(gm.dataTable, {displayAnnotations: true});

}

С этим телом HTML

<input type="button" onclick="printGraph()" value="Draw Graph">
<div id='chart_div' style='width: 800px; height: 350px;'></div>

Проблема: я получаю сообщение об ошибке "Ожидается объект" в строке gm.addSet(title). В принципе, я не могу использовать класс GraphManager. Что я здесь делаю неправильно?


person imagineblue    schedule 16.07.2010    source источник
comment
Где части приведенного выше кода включены в вашу HTML-страницу?   -  person R. Hill    schedule 16.07.2010
comment
Я добавил это ниже для справки, спасибо   -  person imagineblue    schedule 17.07.2010


Ответы (3)


Разве не должно быть «dataTable» вместо «tableData»?

for (var i = place + 1; i<tableData.count; i++)
{
    column[i] = undefined;
}
person R. Hill    schedule 16.07.2010

Я не знаю, согласно:

http://code.google.com/apis/visualization/documentation/reference.html#DataTable

count не является атрибутом, но я вижу, что вы ссылаетесь на него во многих местах своего кода:

var column = new Array(dataTable.count)

Однако существует dataTable.getNumberOfColumns()

person R. Hill    schedule 16.07.2010
comment
Спасибо, это верно, я исправил это, но у меня все еще есть ошибка ожидаемого объекта - person imagineblue; 16.07.2010

Хорошо, я понял проблему. По сути, я пропустил кучу операторов «это», и когда я создал новую дату, я использовал квадратную скобку вместо круглых скобок. Я также понял, что когда я добавлял новый набор данных, мне нужно было просмотреть старые данные, чтобы добавить пустые столбцы. Вот готовый код, если кому-то интересно... Это очень полезно, если вы добавляете данные в разные даты или если вы не знаете, сколько наборов данных у вас будет.

 function GraphManager(adataTable)
 {
     this.graphData = new Array();
     this.dataTable = adataTable;

     this.titleFinder = new Object(); // used to keep track of the indices

     this.dataTable.addColumn('date', 'Date');

     this.addSet = function(title)
     {

         var setCount = (this.dataTable.getNumberOfColumns() -1) / 3; //used for the column name
         var pointsCount = this.graphData.length;
         var place = this.dataTable.getNumberOfColumns();

         this.titleFinder[title] = place; //the title of the column and its location

         this.dataTable.addColumn('number', title);
         this.dataTable.addColumn('string', 'title' + setCount);
         this.dataTable.addColumn('string', 'text' + setCount);

         var newCount = this.dataTable.getNumberOfColumns();



         for (var i = 0; i<pointsCount; i++)
         {
             for (var j=place; j<newCount; j++)
             {
                 this.graphData[i][j] = undefined;
             }


         }  

     }

     this.addPoint = function(title, date, number)
     {
         //this function finds the location of the category
         //and inserts a column with data at the location


         var place = this.titleFinder[title]; //get the location

         var column = new Array(this.dataTable.getNumberOfColumns()); 
         column[0] = date;
         column[place] = number;

         for (var i = 1;i<place; i++)
         {
            column[i] = undefined; 
         }

         for (var i = place + 1; i<this.dataTable.getNumberOfColumns(); i++)
         {
             column[i] = undefined;
         }

         var next = this.graphData.length;
         this.graphData[next] = column;
         this.dataTable.addRows(this.graphData);

     }


 }

И его так же легко использовать, как это:

     var data = new google.visualization.DataTable();
     var gm = new GraphManager(data);

     var title = "testcategory";
     var title2 = "cat";

     gm.addSet(title);
     gm.addPoint(title, new Date(2010, 5, 10), 100);
     gm.addPoint(title, new Date(2010, 6, 10), 200);
     gm.addPoint(title, new Date(2010, 2, 10), 300);


     gm.addSet(title2);
     gm.addPoint(title2, new Date(2010, 6, 10), 100);
     gm.addPoint(title2, new Date(2010, 2, 10), 500);

     var chart = newgoogle.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
     chart.draw(gm.dataTable, {displayAnnotations: true});
person imagineblue    schedule 16.07.2010