Javascript模块之间共享的全局变量

时间:2014-05-07 14:46:59

标签: javascript module revealing-module-pattern

我有一个脚本,我想分开到多个模块。 例如,将我的所有鼠标事件放在另一个模块中(mouseup,mousedown等)。

我使用一堆全局变量来跟踪屏幕上的所有对象。鼠标模块需要访问这些变量并更改它们。我意识到我可以揭示其他模块所需的每个变量,但是它们无法改变它们。

如何使用Javascript实现最佳效果?我目前使用揭示模块模式,并且我读到我必须使用getter和setter(例如我从学校回忆的C ++中使用的),但是我有很多全局变量需要跟踪。我需要这些方法中的一些。这是我应该这样做的方式吗?

或......这是一个案例,告诉我一个问题描述了糟糕的设计。

我使用Fabric.js来完成绘图和所有这些工作。

drawscript.js

var DrawScript = function(){

    var DRAW = 0,
        SELECT = 1,
        SCROLL = 2;

    var MOUSEBUTTONS = {
        'S': 83,
        'C': 67,
        'D': 68,
        'DELETE': 46,
        'BACKSPACE': 8
    };

    var canvas;
    var _started       = false;
    var _x, _y;
    var square;
    var edgedetection  = 10; // pixels to snap
    var lines          = {};
    var lines_group;
    var rectangles_group;
    var rectangle_txt  = {};
    var _text_offset_x = 20;
    var _text_offset_y = 20;
    var pressedKeys    = [];

    var _stroke_colour_var    = "red";
    var _stroke_width_var     = 5;
    var _selectionColor       = "rgba(255,255,255,0.4)";
    var _selectionBorderColor = "rgba(0,0,0,0.5)";

    var selectedObjStartSettings = {};
    var resetOpacityOfObject     = false;
    var drawingMode              = true;
    var mouseGlobal              = null;
    var garbage                  = null;

    var window_height        = 0;
    var window_width         = 0;
    var canvasHeight         = 0;
    var canvasWidth          = 0;
    var bg_height            = 0;
    var _canvas_position = {
        'x': {},
        'y': {}
    };
    var _canvas_mouse_pos_x = 0;
    var _canvas_mouse_pos_y = 0;

    var _fullSizeOn      = false;
    var _fullWidth       = 0;
    var _fullHeight      = 0;
    var _fitWidth        = 0;
    var _fitHeight       = 0;
    var _scaleSizeWidth  = 0;
    var _scaleSizeHeight = 0;

    var setCanvasSize = function(){
        // stuff
    },

    checkDrawingMode = function(){
        // stuff
    },

    checkKeyDown = function(e){
        // stuff
    },

    saveDrawing = function(){
        // stuff
    },

    deleteObjectFromCanvas = function (obj){
        // stuff
    },

    setObjectStartPoints = function(){
        // stuff
    },

    drawNewRect = function(top, left, width, height, name){
        // stuff
    },

    updateCoords = function(x, y){
        // stuff
    },

    changeZoom = function(input){
        // stuff
    },

    init = function(){

        garbage = $("#garbage");

        // ===================================
        //  Set drawing mode when changed
        // ===================================
        $("input[name='draw']").change(function(){
            checkDrawingMode();
        });

        // ===================================
        //  Zoom On
        // ===================================
        $("input[name='zoom-on']").change(function(){
            changeZoom(this);
        });

        // ===================================
        //  Check keypress
        // ===================================
        $(document).keydown(function(e){
            checkKeyDown(e);
        });

        $(document).keyup(function(e){
            e.preventDefault();

            var key;

            if(e.metaKey)
            {
                // key = 91;
                return;
            }
            else
                key = e.keyCode;
            pressedKeys[key] = false;

            // console.log(pressedKeys);
        });

        // ===================================
        //  Save drawing
        // ===================================
        $("#save").click(function(){
            saveDrawing();
        });

        $(window).resize(function(){
            setCanvasSize();
        });

        // ===================================
        //  Create canvas and check drawing mode when launched
        // ===================================
        canvas = new fabric.Canvas('demoCanvas');
        setCanvasSize();
        checkDrawingMode();
        canvas.selectionLineWidth = 2;
        canvas.selectionDashArray = [4, 4];
        canvas.cornerColor        = "#900";
        canvas.hoverCursor        = 'pointer';
        canvas.moveCursor         = 'pointer';
        canvas.selection          = false;

        // ===================================
        //  Add groups
        // ===================================
        rectangles_group = new fabric.Group();
        lines_group = new fabric.Group();
        canvas.add(lines_group);

        // ===================================
        //  Get mouse events
        // ===================================
        canvas.on('mouse:down', function(options) { mousedown(options); });
        canvas.on('mouse:move', function(options) { mousemove(options); });
        canvas.on('mouse:up', function(options) { mouseup(options); });
        canvas.on('object:scaling', function(e) { e.target.resizeToScale(rectangle_txt, _text_offset_x, _text_offset_y); });
        canvas.on('object:selected', function() { setObjectStartPoints(); });
        canvas.on('object:moving', function(options) { objectMoving(options); });
    };

    return {
        init: init
    };

}();

为了简洁起见,我已删除了顶部的功能实现。 另外,我肯定需要在命名约定方面使我的变量名更加统一。这一切都很早,所以我很抱歉,如果这让任何人想要破坏我的膝盖!

我不确定如何分割鼠标事件,因此我的drawScript.js文件不会变成3k行。鼠标事件都使用各种组和坐标变量I设置。此外,我需要在应用程序使用的脚本中共享画布。

也许我只是想努力和过度组织,但我认为寻求帮助可以帮助我在更大的项目中变得更好:)

1 个答案:

答案 0 :(得分:2)

请勿使用Revealing Module Pattern。许多人从Addy Osmani's book学习了揭示模块模式而没有关注Addy's warning

正如您所知,当您将关闭的变量显示给其他模块时,它们无法更改。这是揭示模块模式的根本弱点。你可能做过这样的事情

var mouse = (function(){
  var x = 10, y = 20;
  var drawLineTo = function(x1,y1){
     console.log("Drawing line from " + x + "," + y + " to " + x1 + "," + y1);
  };
  return {
     x: x,
     y: y,
     draw: drawLineTo
  }

})

mouse.x = 50
mouse.draw(15,15) // print "Drawing line from 10,20 to 15,15"

并发现更改mouse.x不会更改闭包中x的值。虽然你可以通过定义明确的getter和setter来解决这个问题

var mouse = (function(){
  var x = 10, y = 20;
  var getX = function() {return x};
  var setX = function(val) {x = val};
  var drawLineTo = function(x1,y1){
     console.log("Drawing line from " + x + "," + y + " to " + x1 + "," + y1);
  };
  return {
     getX : getX,
     setX : setX,
     y: y,
     draw: drawLineTo
  }

})

mouse.setX(50);
mouse.draw(15,15) // print "Drawing line from 10,50 to 15,15"

使用Revealing Module Pattern只是一个愚蠢的代价。更简单的是

var mouse = (function(){
  // put your private variables and methods here.
  return {
     x : 10,
     y: 20,
     draw: function(x1,y1){
        console.log("Drawing line from " + this.x + "," + this.y + " to " + x1 + "," + y1)
     }
  }

})

mouse.x = 50;
mouse.draw(15,15) // print "Drawing line from 50,20 to 15,15"

关键是永远不要透露 - 只将你打算隐藏的东西放入封口。意图公开的事情应该这样创造。