zoukankan      html  css  js  c++  java
  • knockout+echarts

     

    v一、需要学习的知识

      knockout, require, director, echarts, jquery。简单的入一下门,网上的资料很多,最直接就是进官网校习。

    v二、效果展示

    v三、require的配置

      require.config.js中可以配置我们的自定义模块的加载。

    复制代码
    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"
        }
    });
    复制代码

      当前项目目录结构如下。

      没有配置路由的index.html如下。

    复制代码
    <!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>
    复制代码

      这样,所有的模块都是可以被找到被加载的。

      现在改变一些目录结构,在根目录下新建index文件夹,将index.html放入该文件夹下。并修改index.html中script的引用路径,如下。

    复制代码
    <!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>
    复制代码

      目录结构如下

      重新用浏览器打开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:"../"就可以了。

    v四、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个定义好的模块,如下。

    v五、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; 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;  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(自定义模块),接下来看看我们自定模块的内容。

    v六、自定模块(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被加载并调用。

    v七、异常处理

      在用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

      

    v八、完整demo

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

     
    分类: JS工具
     
    好文要顶 关注我 收藏该文  
    3
    0
     
    (请您对文章做出评价)
     
    « 上一篇:深入分析Spring 与 Spring MVC容器
    posted @ 2016-07-15 21:48 小眼儿 阅读(299) 评论(0) 编辑 收藏
     
  • 相关阅读:
    【POJ 1958】 Strange Towers of Hanoi
    【HNOI 2003】 激光炸弹
    【POJ 3263】 Tallest Cow
    【POJ 2689】 Prime Distance
    【POJ 2777】 Count Color
    【POJ 1995】 Raising Modulo Numbers
    【POJ 1845】 Sumdiv
    6月16日省中集训题解
    【TJOI 2018】数学计算
    【POJ 1275】 Cashier Employment
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/5679474.html
Copyright © 2011-2022 走看看