2012-10-05 32 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; 
};