未加星标

Let's Refactor Some of My New, Bad Code: Part 1

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二03 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

I've been on a refactoring tear lately, having refactored some code I found on the Internet for use in a rainflow application and some old code of my own from one of my college courses . I had so much fun doing those posts that I thought I'd round out the trilogy with one more refactoring exercise, this time on some code I've written recently, and horribly. The code comes from the javascript code I wrote for this blog in the Everyday DSP for Programmers series. All of the DSP graphs in that series used the html5 canvas and the PixiJS 2D rendering library to draw the moving plots that I used as visual aides. I wrote quite a bit of crappy JavaScript, or rather, copied quite a bit of crappy JavaScript to make those graphs. I unapologetically copied my code from one graph to another and added tweaks to get what I wanted for each example animation, making that the most non-DRY code I've ever written.

It's time to clean up that code, and I'm going to walk through those changes here as I make them. My goals for this exercise are a little more focused because I don't expect to have many issues with the formatting or naming this time around. The code is too recent for that, as I tend to be happy with the formatting and naming of my more recent code. I do expect to address the following issues, though:

There was a problem with activating animations on touch screens that should be fixed. There are magic numbers all over the place. Those should be contained in constants and configurations. Shame on me There's duplication all over the place; shame on me again (and again and again).

What I really want to do here is make an API for drawing animated graphs. I also wanted to make tests for this API, since the current code has no tests, but I quickly discovered that writing automated tests for code that draws in a browser canvas is no easy feat. The part of the code that I could easily test without spending weeks of my precious evenings figuring it out was trivial, so I'm going to go with the good old-fashioned method of testing. I'm going to use my eyes. They were build for this kind of visual inspection anyway. I think it's time to get started.

Fixing Touchscreen Support

As it turns out, I already have a small, ugly start to the API because at some point during the writing of the DSP series, I got tired of copying all of that code from one graph to another and seeing it bloat more and more. I started pulling out some of the easiest, most used functions into a separate include file. This file lives in my github.io repo as dsp_graphing.js, and it contains some useful functions for drawing different types of axes and a sine curve generator. It's a start, but it's filled with magic numbers specific to drawing graphs at the size I was using for my blog posts, and, well, yeah, it's really ugly. We'll fix it up, though. The github.io repo will show the refactorings that were done to improve it.

Before we get into the nitty-gritty of refactoring and fleshing out the API, I want to fix that first issue of my graphs not reacting to touch events. I spent a lot of time trying to figure this out the first time writing all of these DSP posts, and I spent a fair amount of time again now, finally figuring it out. Like all good bugs, it was pretty simple in the end. It turns out I was trying to attach an event handler to a canvas event that didn't exist.

How did this happen? Well, PixiJS allows you to add event handlers to different drawing objects in the canvas you're drawing on, and the events have names like 'click' for a mouse click or 'tap' for a touchscreen tap. I was using these names, but I was attaching the handlers to the canvas instead of a PixiJS drawing object because I couldn't get the events to work when I attached the handlers to a drawing object. The 'click' event happened to work because it's the same name for the HTML5 canvas, but the corresponding 'tap' event for the canvas is 'touchend' . Once I figured that out and made the fix, I finally had support for touch screens. Here's what the initialization code looks like for starting up PixiJS on a canvas and adding events:

$(function() { var canvas = $('#canvas-sine-offset'); var renderer = PIXI.autoDetectRenderer(canvas.width(), canvas.height(), { antialias: true }); canvas.append(renderer.view); canvas.on('click', onClick); canvas.on('touchend', onClick); $('canvas').css('border-radius', 5); // ... });

This initialization code is the same for every graph, so I'm going to pull it into a function in my API:

function initCanvas(id, eventHandler) { var canvas = $(id); var renderer = PIXI.autoDetectRenderer(canvas.width(), canvas.height(), { antialias: true }); canvas.append(renderer.view); canvas.on('click', eventHandler); canvas.on('touchend', eventHandler); $('canvas').css('border-radius', 5); return renderer; }

Now I can call this function to initialize the canvas for each graph like so:

var renderer = initCanvas('#canvas-sine-offset', onClick);

There's a problem brewing here that should be addressed. As I continue to add functions to my API, I'm actually adding them to the global namespace. The more functions I add, the more likely I'm going to get collisions with other names in the global namespace. I should wrap up these API functions in a module so they can be accessed through the module name instead. That's easy enough to do:

var dsp_graph = (function() { return { initCanvas: function(id, eventHandler) { var canvas = $(id); var renderer = PIXI.autoDetectRenderer(canvas.width(), canvas.height(), { antialias: true }); canvas.append(renderer.view); canvas.on('click', eventHandler); canvas.on('touchend', eventHandler); $('canvas').css('border-radius', 5); return renderer; } } }());

I can add the other API functions into this list of functions in the return block, and then I have to go and change all of the calls to these functions on every blog post to include the module name, e.g. dsp_graph.initCanvas . It's a lot of tedious work, but it'll be worth it as I add more functions to the API and refactor the functions that are already there to extract configuration variables and constants. Once that's done, I can inspect the graphs for correctness and commit the code .

Refactoring the Current API

Things are already looking better. Now it's time to tackle the current API monstrosity and make it a little more sane. The main part of the API is a set of four functions that draw different types of axes for the graphs. The first one is drawPositiveAxis() :

drawPositiveAxis: function(stage, x_labels, y_labels) { var graphics = new PIXI.Graphics(); graphics.lineStyle(1, 0xdddddd, 1); graphics.moveTo(15, 280); graphics.lineTo(535, 280); for(var x = 41; x <= 535; x += 26) { graphics.moveTo(x, 275); graphics.lineTo(x, 280); } graphics.moveTo(15, 20); graphics.lineTo(15, 280); for(var y = 20; y < 280; y += 26) {

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: JavaScriptJavaHTMLHTML5RY
tags: canvas,code,API,var,my,functions
分页:12
转载请注明
本文标题:Let's Refactor Some of My New, Bad Code: Part 1
本站链接:http://www.codesec.net/view/530737.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(75)