knockoutJS动态图表与高图表 [英] knockoutJS dynamic chart with high charts

查看:124
本文介绍了knockoutJS动态图表与高图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,过去一周我一直在玩高图和KO。高图表的语法非常简单易读。

So, I have been playing with high charts and KO for the past week. The syntax for the high charts graph is very simple and easy to read.

我来自Java,我对JS很新,所以我不知道如何真正发挥作用。

I'm coming from Java and I am pretty new to JS, so I'm not sure how to really play with the scope.

有没有使用或组合淘汰与高图表轻松制作动态图?我可以把它们放在同一个JS文件中吗?

Is there anyway to use or combine knockout with high charts to easily make a dynamic graph? Can I simply put them in the same JS file?

高图表代码看起来很简单,必须有一个简单的解决方案!感谢您的输入/帮助!

The high charts code looks so simple there has to be an easy solution! Thanks in advance for the input/help!

以下是我的高图表图形的代码:

Here is the code for my high charts graph:

$(function() {
    var chart;
    //alert(users);
    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart : {
                renderTo : 'container',
                type : 'line',
                marginRight : 130,
                marginBottom : 25
            },

            title : {
                text : 'Body Weight',
                x : -20 //center
            },
            xAxis : {
                categories : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
            },

            yAxis : {
                title : {
                    text : 'Weight (lbs)'
                },
                plotLines : [{
                    value : 0,
                    width : 1,
                    color : '#808080'
                }]
            },
            tooltip : {
                formatter : function() {
                    return '<b>' + this.series.name + '</b><br/>' + this.x + ': ' + this.y + 'lbs';
                }
            },
            legend : {
                layout : 'vertical',
                align : 'right',
                verticalAlign : 'top',
                x : -10,
                y : 100,
                borderWidth : 0
            },
            series : [{
                name : 'George',
                data : [185,190,185,180]
            }, {
                name : 'Bindu',
                data : [115,110,112,115]
            }, {
                name : 'Phil',
                data : [195,190,190,185]
            }]
        });
    });
});

这里是我的KO模型:

/*
 * Reading class
 * containts health readings
 */
function Reading(date,weight,glucose)
{
    var self = this;

    self.date=ko.observable(date);
    self.weight=ko.observable(weight);
    self.glucose=ko.observable(glucose);
    self.readingId=ko.observable(0);

      self.formattedWeight = ko.computed(function(){
        var formatted = self.weight();

        return formatted+" lb"
    });
}

/*
 * User class
 * contains a user name, date, and an array or readings
 */
function User(name,date,readings) {
    var self = this;

    self.name = name;
    self.date = date;
    self.userId = ko.observable(0);
    self.readingsArray = ko.observableArray([
        new Reading(99,22,88),new Reading(11,22,33)
    ]); 
}
// Overall viewmodel for this screen, along with initial state
function userHealthModel() {
    var self = this;
    self.inputWeight = ko.observable();
    self.inputDate = ko.observable();
    self.inputId = ko.observable();
    self.inputGlucose = ko.observable();

    // Operations
    self.subscribe = function(){
        var users = this.users();
        for(var x = 0; x < users.length; x++)
        {
            self.users()[x].userId(x); 
        }

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

   self.removeUser = function(userName){
    self.users.remove(userName);
    self.subscribe();}

     //adds a readings to the edittable array of readings (not yet the reading array in a user)
    self.addReading = function(){
        var iD = self.inputId();
        var date = self.inputDate();
        var weight = self.inputWeight();
        var glucose = self.inputGlucose();
        if((weight&&date)||(glucose&&date))
        {
            self.users()[iD].readingsArray.push(new Reading(date,weight,glucose));
            self.readings.push(new Reading(date,weight,glucose));
        }
        else{
            alert("Please complete the form!")
        }
    }
    self.removeLastReading = function(userName){
        var lastIndex = (userName.readingsArray().length)-1;
        var removeThisReading = userName.readingsArray()[lastIndex];
        userName.readingsArray.remove(removeThisReading);
    }


    //editable data
     self.readings = ko.observableArray([
        new Reading(12,99,3),new Reading(22,33,2),
        new Reading(44,55,3)
    ]);

      self.users = ko.observableArray([
        new User("George",2012),new User("Bindu",2012)
    ]);
    self.subscribe();

}


推荐答案

与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.

希望这有帮助。

这篇关于knockoutJS动态图表与高图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆