2010-11-29 71 views
0

你好我正在寫一些jquery插件,我讀了一些教程,發現全部清晰。但是我找不到解釋如何添加事件的教程(更好的說是調用函數),例如我想調用myplugin打開事件的函數。我想做類似於jquery對話事件的事情,就像開放事件一樣:創建jquery插件

$('#adialog').dialog({ 
    open:function() 
    { 
    //I know this will be called on open of a dialog, how to do in my plugin? 
    } 
}); 

所以我想擁有的是這樣的:

$('#somediv').myplugin({ 
    onOpen:function()// this is not clear how to do it in plugin 
    { 
    //do stuff here 
    }, 
    background-color:'red',//this is clear, $.extends defaults options 
    text:'blablabla',// this is clear $.extends defaults options 
    ......... 
}); 

我想簡單地懂得「事件」添加到我的插件,其中「事件」代表插件的事件的方法,只是舉例在http://jqueryui.com/demos/draggable/#events「事件」選項卡中有可以執行某些功能的事件。

回答

1

回調函數在從正常功能無法區分,並且可以被稱爲等任何其它方法。

然而,如果回調是可選的,你應該檢查它在調用它來避免運行時錯誤依舊存在。

例如:

$.fn.myPlugin = function(options) { 
    if (options.onOpen)  //If the callback was passed, 
     options.onOpen(...); 
}); 
+0

是好感謝 – albanx 2010-11-29 20:54:03