knockout+echarts實現圖表展現

1、須要學習的知識

  knockout, require, director, echarts, jquery。簡單的入一下門,網上的資料不少,最直接就是進官網校習。css

2、效果展現

3、require的配置

  require.config.js中能夠配置咱們的自定義模塊的加載。html

require.config({
    baseUrl: ".",
    paths: {
        text: "requirejs/text",
        jquery: "jquery/jquery-1.11.2",
        jqueryconfirm:"jquery/jquery-confirm",
        knockout: "knockout/knockout-3.2.0.debug",
        director:"director/director",
        echarts: "echarts/echarts.min"
    }
});

  當前項目目錄結構以下。jquery

  沒有配置路由的index.html以下。git

<!DOCTYPE html>
<html>
    <head>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>widget</title>
        <meta charset="utf-8" />
    </head>
    <body>
        <div>
            <div id="content">
            </div>
        </div>
    </body>
    <script src="requirejs/require.js"></script>
    <script src="js/require.config.js"></script>
    <script src="js/index.js"></script>
</html>

  這樣,全部的模塊都是能夠被找到被加載的。github

  如今改變一些目錄結構,在根目錄下新建index文件夾,將index.html放入該文件夾下。並修改index.html中script的引用路徑,以下。ajax

<!DOCTYPE html>
<html>
    <head>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>widget</title>
        <meta charset="utf-8" />
    </head>
    <body>
        <div>
            <div id="content">
            </div>
        </div>
    </body>
    <script src="../requirejs/require.js"></script>
    <script src="../js/require.config.js"></script>
    <script src="../js/index.js"></script>
</html>

  目錄結構以下chrome

  從新用瀏覽器打開index/index.html,而後會發現瀏覽器控制檯報錯: 項目根目錄/index/jquery/jquery-1.11.2.js net::ERR_FILE_NOT_FOUND, 固然require.config.js中加載的其餘的模塊也找不到了。因此說,require.config.js中的baseUrl: "."表示的是當前根目錄爲index.html所在的目錄。若是如今的目錄結構想要正確的加載模塊,那麼修改爲baseUrl:"../"就能夠了。json

4、director進行路由

  index.js內容以下。跨域

require(['jquery', 'knockout', 'director'],function ($,ko){
    window.addRouter = function(path, func) {
        var pos = path.indexOf('/:');
        var truePath = path;
        if (pos != -1)
            truePath = path.substring(0,pos);
        func = func || function() {
            var params = arguments;
            initPage('pages' + truePath, params);
        }
        var tmparray = truePath.split("/");
        if(tmparray[1] in router.routes && tmparray[2] in router.routes[tmparray[1]] && tmparray[3] in router.routes[tmparray[1]][tmparray[2]]){
            return;
        }else{
            router.on(path, func);
            if (pos != -1)
                router.on(truePath, func);
        }
    }

    window.router = Router();
    
    $(function(){
        addRouter("/pie/pie");
        addRouter("/pie2/pie");
        addRouter("/dashBoard/board");
        window.router.init();
    });  

    function initPage(p, id) {
        var module = p;
        requirejs.undef(module);
        require([module], function(module) {
            ko.cleanNode($('#content')[0]);
            $('#content').html('');
            $('#content').html(module.template);
            if(module.model){
                ko.applyBindings(module.model, $('#content')[0]);
                module.init(id);
            }else{
                module.init(id, $('#content')[0]);
            }
        })
    }

});

  index.js中,定義了addRouter函數,這個函數主要是用來添加路由,首先判斷有沒有被添加過,而後爲每個路由指定一個回調函數,回調函數會調用咱們的initPage()方法,經過require加載咱們定義好的模塊。瀏覽器

  咱們的pages目錄下有3個定義好的模塊,以下。

5、index.html中配置路由url

 

  在index.html添加url路徑信息,以下。

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="index.css">
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>widget</title>
        <meta charset="utf-8" />
    </head>
    <body>
        <div style="float: left; width:15%; margin-top: 50px;">
            <div class='card-holder'>
              <div class='card-wrapper'>
                <a href='#/pie/pie'>
                  <div class='card bg-01'>
                    <span class='card-content'>普通圖表</span>
                  </div>
                </a>
              </div>
              <div class='card-wrapper'>
                <a href='#/pie2/pie'>
                  <div class='card bg-02'>
                    <span class='card-content'>嵌套環形圖</span>
                  </div>
                </a>
              </div>
              <div class='card-wrapper'>
                <a href='#/dashBoard/board'>
                  <div class='card bg-03'>
                    <span class='card-content'>開車開車</span>
                  </div>
                </a>
              </div>
            </div>
        </div>
        <div id="content" style="float: left; width: 75%; margin-top: 50px;">
            <h1 style="text-align: center;">歡迎使用ECharts!</h1>
        </div>
    </body>
    <script src="requirejs/require.js"></script>
    <script src="js/require.config.js"></script>
    <script src="js/index.js"></script>
</html>

  index.js執行以後會將路由註冊到director中的Router中,用戶點擊連接,好比<a href='#/pie/pie'>,就會觸發 /pie/pie 這個路由對應的回調方法,回調方法中會執行initPage('pages' + truePath, params), truePath="/pie/pie",接着require就會完成加載pages/pie/pie.js(自定義模塊),接下來看看咱們自定模塊的內容。

6、自定模塊(echart-餅圖)

  pages/pie/pie.js內容以下。

define(['jquery', 'knockout', 'text!pages/pie/pie.html', 'echarts'], function($, ko, template, echarts){
    var viewModel = {
        pieData: ko.observableArray([]),

        setData: function(data){
            this.pieData(data);
        },

        viewPie: function(){
            //提取name
            var names = [];
            for(var val of this.pieData())
                names.push(val.name);

            // 基於準備好的dom,初始化echarts實例
            var myChart = echarts.init(document.getElementById('main'));
    
            // 指定圖表的配置項和數據
            var option = {
                title : {
                    text: '某站點用戶訪問來源',
                    subtext: '純屬虛構',
                    x:'center'
                },
                tooltip : {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    data: names
                },
                series : [
                    {
                        name: '訪問來源',
                        type: 'pie',
                        radius : '55%',
                        center: ['50%', '60%'],
                        data: this.pieData(),
                        itemStyle: {
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };
            myChart.setOption(option);
        },

        load: function(){
            var self = this;
            $.ajax({
                type: 'post',
                url: 'pages/pie/data.txt',
                dataType: 'json',
                success: function(data){
                    self.setData(data.pieData);
                    self.viewPie();
                },
                error: function(data){
                    alert("error: " + JSON.stringify(data));
                }
            });
        }
    }
    var init = function(){
        viewModel.load();
    }

    return {
        'model' : viewModel,
        'template' : template,
        'init' : init
    };
});

   自定義模塊中,require會加載jquery(調用ajax加載數據),knockout(數據綁定),text(須要渲染的html頁面),echarts(圖表展現),最後的return返回的對象會在index.js中initPage()方法經過require被加載並調用

7、異常處理

  在用jquery的ajax請求本地資源時,可能會出現 Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource。

  解決方法:給瀏覽器傳入啓動參數(allow-file-access-from-files),容許跨域訪問。Windows下,運行(CMD+R)或創建快捷方式:"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe" --allow-file-access-from-files

  

8、完整demo

  https://github.com/hjzgg/knockout-and-echart

相關文章
相關標籤/搜索