2013-12-23 54 views
1

我有這個被監聽一個撥動開關進行更改,並調用一些AJAX:功能來初始化聽衆

$('#notificationStatusBtn').on('switch-change', function(e, data) {  
     if(data.value == true){   
      $.get("myURL"); 
     }else{ 
      $.get("myURL"); 
     } 
    }) 

這工作得很好,但我真的不喜歡爭論風格中的函數。所以我試圖折射它:

$(document).ready(initListeners()); 

    //Intialize button listeners  
    function initListeners(){ 
     $('#notificationStatusBtn').on('switch-change', setNotificationStatus(e, data)); 
    } 

    function setNotificationStatus(e, data){ 
     if(data.value == true){   
      $.get("muURL",function(data,status){ 
        alert("Data: " + data + "\nStatus: " + status); 
      }); 
     }else{ 
      $.get("muURL",function(data,status){ 
        alert("Data: " + data + "\nStatus: " + status); 
      }); 
     } 

但我的返工代碼不起作用。

+2

而不是'$(文件)。就緒(initListeners());'用'$(initListeners)' –

回答

2

你的回調是不正確的setNotificationStatus。回調是對你的函數的引用,因此不需要變量e和數據。

嘗試刪除他們,你有:

$('#notificationStatusBtn').on('switch-change', setNotificationStatus); 

你也犯同樣錯誤的文件準備好處理程序:

$(document).ready(initListeners()); 

變爲:

$(document).ready(initListeners); 

不要如果在調試時不敢使用警報語句,那麼它有時會用作快速和骯髒的檢查。如果你想保留你的調試信息,你可以移動到console.log。

HTH

+0

與同爲準備處理程序 –

2
$('#notificationStatusBtn').on('switch-change', setNotificationStatus(e, data)); 

您是調用該函數這裏,不是將它作爲一個參數。注意括號。

你可以嘗試,而不是:

$('#notificationStatusBtn').on('switch-change', setNotificationStatus); 

您也有同樣的問題在這裏:

$(document).ready(initListeners()); 

記住,每當一個函數名後有括號,你是調用功能。當將它們作爲參數傳遞時,您可以簡單地將函數作爲任何其他變量來處理。

下面是一個例子控制檯會話,這樣可以很清楚:

> function test() { return 4; }; 
undefined 
> test 
function test() { return 4; } 
> test() 
4