2013-11-21 36 views
0

我有我需要的時候我傳遞一個可選的參數運行的功能,但它的主要作用AJAX調用是由點擊事件觸發。我試過trigger()函數沒有成功。處理這種情況的最佳方法是什麼?繞過jQuery的單擊事件參數

function call_stuff() 
{ 
    $items = []; 
    $(this).closest('tr').children().each(function() { 
     $items.push($(this).text()); 
    }); 
    do_stuff($items); 

} 

function do_stuff(items) { 

    if (typeof items === 'undefined') { 
     //regular execution listen for click command 
     // use $(this) for ajax data 
    } else { 
     //ignore click command, run ajax function. 
     //use $items for ajax data 

    } 

    $(".tabs-parent li a, .tabs-child li a").click(function() { 
     //the ajax call I need to run: 
     $.ajax({ 
      data: {} 
     }) 

    }); 


} 

回答

1

依託觸發事件,以按需執行一些邏輯在我看來是一種常見的設計錯誤。您的設計將是第一次封裝在另一個函數的行爲,然後你就可以隨意調用更清潔和更靈活。

function doSomething() { 
    console.log('do something'); 
} 

//adding the handler 
$('#myEl').click(function() { 
    doSomething(); 
}); 

//or without the adapter function it not necessary 
$('#myEl').click(doSomething); 

//calling at will 
doSomething(); 

注:我不主張在全局命名空間來聲明功能。你應該保持你的代碼模塊化並正確的範圍。

+0

是的,這是一個有趣的概念,但是每次觸發點擊時我都必須將引用傳遞給$(this)。 – Edward

+0

@Edward那麼使用相同的方法和封裝你想在一個函數,這不是處理程序的一部分運行的邏輯。我看不出有什麼問題。您的職能應遵循單一的責任原則。然後,它可以很容易的執行只需要沒有任何代碼重複執行的。 – plalx

+0

生病嘗試一下謝謝 – Edward