Paul
Paul

Reputation: 5924

KendoUI for jQuery - Chart dataBound event does not work

Here's a simplified example of my data:

[{"Name": "Bob", "Count":3}, {"Name": "Steve", "Count":5}]

What I want is a chart title of: Total FOO: 8. So the title must be based on the data. The data is AJAX and this is an ASP.NET MVC application.

In my CSHTML I have:

.DataSource(ds => ds.Read(read => read.Action("MeMethodName", "MyControllerName")))
.Events(events => events.DataBound("setChartTitle('chartName', 'Total FOO')"))

Here's the crazy hack I had to do:

   function setChartTitle(name, title) {
      let chart = $("#" + name).data("kendoChart");
      if (chart) {
         let ds = chart.dataSource;
         let total = 0;
         for (let i = 0; i < ds.data().length; i++) {
            total += ds.data()[i].Count;
         }

         chart.options.title.text = title + ": " + total;
         chart.refresh();
      } else if (arguments.length < 3) {
         // Data source was not found and this was initiated through Kendo. Wait and try again but only once
         setTimeout(function () {
            sumEntityCount(name, title, "stop");
         }, 500);
      }
   }

This is really bad.

  1. Accessing the kendoChart returns undefined, yet the chart itself called this. This is why I need to check if (chart) above.
  2. This leads to a hacky ELSE block I added where I can call this again with a 500 ms delay. This alone is a bug as 500ms is a random number and may not be enough. I can't ship like this.
  3. To prevent recursion I call the same function with a different parameter.
  4. If the values are found, then I can't just set the chart options. I need to call refresh which redraws everything.

Questions:

  1. Why is the kendoChart data undefined initially? Why has Telerik called dataBound when there's nothing there?!
  2. Isn't there a dataBinding event? I don't want to do this after the fact nor do I want to refresh the whole thing.

Upvotes: 0

Views: 466

Answers (1)

Paul
Paul

Reputation: 5924

The chart itself is passed in when you declare a basic function without calling it:

.events(events => events.Render("someFunction"))

Then declare your function:

function someFunction(sender) {
   // sender.chart is what I want
}

But you cannot pass any arguments here. Which means I can't use it.

The hack is to do the following:

.Events(events => events.Render("function(sender) { someFunction(sender, 'param1', 'param2', 'param3'); }"))

This gives it an actual function instead of calling a function. Kendo passes in the sender as expected and you can pass it along with new parameters to your JavaScript.

I also switched to using Render instead of DataBound.

Upvotes: 0

Related Questions