且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

knockoutJS动态图表与高图表

更新时间:2022-12-03 10:15:51

与KO和Highcharts的经验,但奇怪的是我从未以这种方式组合它们。在内存中简单地保存一个模拟HC的配置对象的KO模型,两个只是玩得很​​好,这将是很好的。不幸的是,这不会发生,因为KO的可观察是功能,HC希望纯json。你可以做到这一点,但你必须每次销毁图表,并重新创建一个未映射的KO模型,所以可能不是你在想的。

I have experience with both KO and Highcharts but weirdly I've never combined them in this manner. It would be nice to simply hold a KO model in memory that mimics the config object of HC and the two just play nice. Unfortunately this isn't going to happen as KO's observables are functions and HC expects pure json. You could do this but you'd have to destroy the chart each time and recreate with an unmapped copy of your KO model so probably not what you were thinking.

当你说动态我假设你的意思是数据?

When you say dynamic I am assuming you mean the data only?

图表/系列对象有一些方法记录在这里,可用于将您的模型连接到图表。一个非常简单而不完整的方法就是这样的。

There are a number of methods on the chart/series objects documented here that can be used to connect your model to you chart. A really simple and incomplete way would be something like.

self.addUser = function() {
    var user = new User("Foo", 0, 0, new Reading(0, 0));
    self.users.push();
    self.subscribe();

    // chart handler
    /// need to convert the readingsArray into a data array
    chart.addSeries({ name: user.name, data: [180, 175, 195, 180] });
}

或者,您可以订阅用户数组并相应更新图表。 (注意,我没有将您的用户读数数据映射到数组,但您得到的想法)

Alternatively you could subscribe to the users array and update the chart accordingly. (Note I didn't map your user readings data to the array but you get the idea)

viewModel.users.subscribe(function() {
  .. update chart here
});

请参阅这里关于订阅观察者的更多细节。

See here for more details on subscribing to observables.

这是我创建的小提琴来测试这个。

Here is the fiddle I created to test this.

http://jsfiddle.net/madcapnmckay/uVTNU/

我怕将模型对象手动映射到highchart的数据格式。

I'm afraid there is going to be a bit of manual mapping of your model objects to highchart's data format.

希望这有帮助。