我正在编写一个 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 函数更好,但在这种情况下如何共享变量?
提前感谢您的帮助
弗雷德