JQuery 插件架构,用于定义对象和变量生命周期

JQuery plugin architecture, where to define objects and variables life cycle?

本文关键字:变量 生命 周期 对象 定义 插件架 用于 JQuery      更新时间:2023-09-26

我正在编写一个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函数,但在这种情况下如何共享变量?

提前感谢您的任何帮助

佛瑞德

所以我

的答案是:

  • 似乎没问题。然而,在你的闭包参数中,你不需要windowdocument,它们是简单的全局变量。只有当您想"重命名"它们时,您才需要它们,例如 globaldoc .我宁愿将该脚本库接口对象作为函数的参数。
  • 是的。但是构造函数是否需要在外部可用?我认为没有。如果您确实需要它们,可以在闭包中声明它们;例如,将它们导出到静态属性中,例如$.render
  • 您需要向我们提供ImageSource代码,否则我们无法回答这个问题
  • 没有在插件中定义任何全局变量(请调整您的评论)。它们是局部的(不是说插件闭包中的"私有"变量,可用于该范围内的其他所有变量。它们的生命周期将结束(使用自动垃圾回收),当没有任何东西(可以)再引用它们时。但是您将一个函数导出到 $.fn.render ,该函数始终具有这些引用。因此,只要导出存在,您的局部变量就会存在。
  • 你应该挂在jQuerys动画队列上。如何在没有.data()的情况下"共享"变量?我会说属于某个(DOM-)节点的所有内容都应该设置为数据属性,否则在启动它后您将无法访问它,对吗?