0

我正在编写一个 jquery 插件来在画布中渲染图像。

最终目标是实现类似

var myImageSource = new ImageSource(path,width,height);
$("#myCanvas").Render({"source" : myImageSource}); 

该插件需要几个类、herpers 和其他一些 jquery 插件才能正常工作。

所以假设我依赖于

  • 鼠标滚轮jQuery插件
  • 一个缓存库,它不是一个 jquery 插件,而是一个带有原型和一些枚举的对象

我有一个动画引擎,它是一个需要全局变量(或至少在插件级别)的循环

function runAnimations(timeStamp) {

    window.requestAnimationFrame(runAnimations);

    for (var i = 0; i < animations.length; i++) {
        animations[i].update(timeStamp);
    }
}

我必须定义我自己的对象

  • 观点
  • 长方形
  • 视口
  • 图像源
  • 动画1

所以我的尝试是这样的:

 - Reference to other script library (like Cache)
 - Reference to other JQuery Plugin

; (function ($, window, document, undefined) {

   //global variable declaration
   var animations = [];
   var isAnimationLoopStarted = false;

   //global functions
   function runAnimations(timeStamp) {

        window.requestAnimationFrame(runAnimations);

        for (var i = 0; i < animations.length; i++) {
            animations[i].update(timeStamp);
        }
    }

   //objects declarations
   function Rect(x, y, height, width) {
      this.x = x;
      this.y = y;
      this.width = width;
      this.height = height;
   }

  Rect.prototype.moveTo = function (x, y) {
      this.x = x;
      this.y = y;
   };

   //other object declarations Point, ImageSource, ViewPort etc..

   //plugin interface
    var methods = {
        init: function () {
            return this.each(function () {

                });
            });
        },
        destroy: function () {
            return this.each(function () {
            });
        }
    };

    $.fn.render = function (method) {
        if (method === 'destroy') {
            return methods.destroy.apply(this);
        } else {
            return methods.init.apply(this);
        }
    }

})(jQuery, window, document);

所以我的问题是:

  • 你觉得走这条路好吗?
  • 如果我这样做,ImageSource 的定义将在插件之外不可用
  • 我是否应该放弃 ImageSource 对象来使用数组,所以我对对象定义没有问题
  • 插件内部定义的全局变量的生命周期是怎样的,比如动画,会一直可用吗?
  • 使用动画之类的变量是最佳做法,还是使用 .data jquery 函数更好,但在这种情况下如何共享变量?

提前感谢您的帮助

弗雷德

4

1 回答 1

0

所以我的答案是:

  • 看起来不错。然而,在你的闭包参数中你不需要windowor document,它们是简单的全局变量。如果你想“重命名”它们,你只需要它们,例如 to globaland doc。我宁愿将该脚本库接口对象作为函数的参数。
  • 是的。但是构造函数需要在外部可用吗?我想不是。如果你真的需要它们,可以在闭包中声明它们;例如将它们导出到静态属性中,例如$.render.
  • 您需要向我们提供 的代码ImageSource,否则我们无法回答该问题
  • 没有在插件中定义任何全局变量(请调整您的评论)。它们是本地的(不是说插件闭包中的“私有”变量,可用于该范围内的所有其他内容。当没有任何东西(可以)再引用它们时,它们的生命周期将结束(自动垃圾收集)。但是你导出一个函数to $.fn.render,它一直都有这些引用。因此,只要该导出存在,您的局部变量就会存在。
  • 你应该挂钩 jQuerys 动画队列。你如何“分享”你的变量没有.data()?我会说属于某个(DOM-)节点的所有内容都应该设置为数据属性,否则在初始化后您将无法访问它,对吗?
于 2012-04-27T08:13:00.400 回答