7. 使用“this”对象
通过使用“$this”,我们可以向别的闭包传递正确的引用。我们也可能需要向别的方法传入 $this 引用。需要注意的是, $this 这个名字是可以改的,任意的变量名都可以。
Canvas.prototype =
{
generate: function()
{
//some code
var $this = this;
var buton = //...some code
button.click(function(){
//using this will not be found since it has it's own this
//use $this instead.
$this.someFunc($this);
});
},
someFunc: function($this)
{
//won't know what "this" is.
//use $this instead passed from the click event
}
}
{
generate: function()
{
//some code
var $this = this;
var buton = //...some code
button.click(function(){
//using this will not be found since it has it's own this
//use $this instead.
$this.someFunc($this);
});
},
someFunc: function($this)
{
//won't know what "this" is.
//use $this instead passed from the click event
}
}
8. 在每一个对象中保存设置
我一直在每一个对象中保存自己的设置,然后操作它自己的设置。这样你就不用在不同的方法中传递很多参数。把这些变量放在对象中,也方便你在其他地方调用这些变量。
function Canvas(settings)
{
this.settings = settings;
return this;
}
{
this.settings = settings;
return this;
}
9. 分离你的Prototype方法逻辑
这可能是一个基本的原则。当你在犹豫是否需要提供一个方法的时候,你可以问你自己 “如果其他人要重写这个方法的话,你的代码是否能满足他的需求?”或者“别人来写这个方法有多困难?”。当然这是一个灵活性拿捏的问题。这里列出了我的 Color Picker jQuery Plugin 的方法,你可以参考一下:
generate()
appendColors()
colorSelect()
colorHoverOn()
colorHoverOff()
appendToElement()
showPalette()
hidePalette()
appendColors()
colorSelect()
colorHoverOn()
colorHoverOff()
appendToElement()
showPalette()
hidePalette()
10. 提供Setter/Getter选项
这一条不是必须的,但是我发现我所有的插件都包用到了这一条。因为它只需要一点点代码,就能为别人提供一个他可能需要的功能。基本上,我们只要让开发者能够设置或者获取元素已经存在的值:
var lineWidth = $("#container").wPaint("lineWidth");
$("#container").wPaint("lineWidth", "5");
$("#container").wPaint("lineWidth", "5");
首先我们要把元素和对象关联起来,然后我们就可以引用它。我们在返回元素之前做如下操作:
return this.each(function()
{
var elem = $(this);
var canvas = new Canvas(settings);
//run some code here
elem.data("_wPaint_canvas", canvas);
}
下面的代码明确了我们究竟要做什么:
$.fn.wPaint = function(option, settings)
{
if(typeof option === 'object')
{
settings = option;
}
else if(typeof option === 'string')
{
if(
this.data('_wPaint_canvas') &&
defaultSettings[option] !== undefined
){
var canvas = this.data('_wPaint_canvas');
if(settings)
{
canvas.settings[option] = settings;
return true;
}
else
{
return canvas.settings[option];
}
}
else
return false;
}
return this.each(function()
{
//run some code here
}
}
{
var elem = $(this);
var canvas = new Canvas(settings);
//run some code here
elem.data("_wPaint_canvas", canvas);
}
下面的代码明确了我们究竟要做什么:
$.fn.wPaint = function(option, settings)
{
if(typeof option === 'object')
{
settings = option;
}
else if(typeof option === 'string')
{
if(
this.data('_wPaint_canvas') &&
defaultSettings[option] !== undefined
){
var canvas = this.data('_wPaint_canvas');
if(settings)
{
canvas.settings[option] = settings;
return true;
}
else
{
return canvas.settings[option];
}
}
else
return false;
}
return this.each(function()
{
//run some code here
}
}