扩展$ .mobile.changePage以接受更多选项?

我想扩展$ .mobile.changePage以接受更多选项,例如在页面完成加载时添加回调函数以及为contentType等AJAX调用添加更多选项。 有没有办法在不更改源代码的情况下执行此操作? 如果没有,我愿意为教育目的更改源代码,但无法在jQuery Mobile GitHub中找到它: https : //github.com/jquery/jquery-mobile 。 感谢您的帮助或指导。

JavaScript中令人兴奋的部分之一是能够使用通常称为Monkey Patching的技术重新定义任何函数。 (另外ES5提供了一种新的冻结方法,允许开发人员防止这种修改。)

这是一个JavaScript MonkeyPatch的例子,它允许我们修改函数的行为而不编辑它的源代码:

 // A namespace object. var Example = {}; // Sums two values. Example.sum = function (a, b) { return a + b; } // Usage: var result = Example.sum(1, 2); 

假设我们想要在sum方法中添加日志记录,我们可以在函数中添加一个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); };