2012-08-15 76 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); 
};