2012-08-15 78 views
1

我想擴展$ .mobile.changePage來接受更多的選項,比如爲頁面完成加載時添加一個回調函數,以及像contentType這樣的AJAX調用的更多選項。有沒有辦法做到這一點,而無需更改源代碼?如果不是,我願意爲教育目的更改源代碼,但無法在jQuery Mobile GitHub中找到它:https://github.com/jquery/jquery-mobile。感謝您的幫助或指導。

+0

剛剛成立的僞頁面被委派'pageshow'或類似的事件處理程序,這是已經存在的功能。 – Jasper 2012-08-15 20:31:29

回答

2

JavaScript中更令人激動的部分之一是能夠使用通常被稱爲Monkey Patching的技術重新定義任何函數。 (順便ES5提供了一種新freeze方法,它允許開發人員能夠防止這樣的修改。)

這裏的一個的JavaScript猴補丁的示例,其允許我們修改函數的行爲,而無需編輯它的源:

// A namespace object. 
var Example = {}; 

// Sums two values. 
Example.sum = function (a, b) { 
    return a + b; 
} 

// Usage: 
var result = Example.sum(1, 2); 

假設我們想記錄添加到數總和法,我們可以只添加一個console.log線的功能,但我們也可以猴子打補丁:

// Store a reference to the current 'Example.sum' function. 
var originalSum = Example.sum; 

// Now redeclare Example.sum... 
Example.sum = function (a, b) { 

    // Call the originalSum function first... 
    var result = originalSum(a, b); 

    // Now add some logging... 
    console.log("Example.sum(" + a + ", " + b + ") yields " + result); 

    return result; 
}; 

現在,當Example.sum是所謂的,不僅我們會像以前一樣得到結果,而且還會寫一個控制檯消息。考慮到這一點,就可以猴子修補$.mobile.changePage方法以同樣的方式:

var originalChangePage = $.mobile.changePage; 

// Redefine `changePage` so it accepts a 'complete' function in the options 
// object which will be invoked when the page change is complete. 
$.mobile.changePage = function (to, options) { 
    if (typeof options.complete === "function") { 
     $(body).one("pagechange", function (event) { 
      options.complete(event); 
     }); 
    } 

    originalChangePage(to, options); 
};