2012-10-05 37 views
2

我已经javascript代码如何编写一般的JavaScript插件

$(function(){ 
    // loading source image 
    $('#panel').mousemove(function(e) { // binding mouse move event 
     // some code 
    }); 
    $('#panel').mousedown(function(e) { // binding mousedown event 
     // some code 
    }); 
    $('#panel').mouseup(function(e) { // binding mouseup event 
     // some code 
    }); 
}); 

function getResults() { 
    // some code 
} 

在这种工作方式

<button onclick="getResults()">Crop</button> 
<canvas id="panel" width="100" height="200"></canvas> 

我想下面重新写这个JS-插件使其更一般化。
我想使用它是通过以下方式一个好办法:

$('#panel').myLib({ 
    onSelect: getResults, 
    onClick: getResults 
}); 

任何想法,我应该如何改写我的js代码来获得这样的结果? 感谢

+1

我建议你开始[这里](http://docs.jquery.com/Plugins /创作) – lanzz

回答

5

使用fn财产(这实际上是prototype的别名)来添加一个插件:

$.fn.myLib = function(options){ 

    // bind events 
    this.mousemove(function(e) { // binding mouse move event 
    // some code 
    }); 
    this.mousedown(function(e) { // binding mousedown event 
    // some code 
    }); 
    this.mouseup(function(e) { // binding mouseup event 
    // some code 
    }); 

    // add a button 
    this.before($('<button>').text('Crop').click(options.onSelect)); 

    // return the object to make the function chainable 
    return this; 
};