扩展$ .mobile.changePage接受更多选项? [英] Extend $.mobile.changePage to accept more options?
问题描述
我想扩展$ .mobile.changePage以接受更多选项,例如在页面完成加载时添加回调函数,以及诸如contentType之类的AJAX调用的更多选项.有没有一种方法可以在不更改源代码的情况下进行此操作?如果没有,我愿意出于教育目的更改源代码,但无法在jQuery Mobile GitHub中找到它: https://github.com/jquery/jquery-mobile .感谢您的帮助或指导.
I would like to extend $.mobile.changePage to accept more options such as adding a callback function for when the page finishes loading as well as more options for the AJAX call like contentType. Is there a way to do this without changing the source code? If not, I am willing to change the source code for educational purposes, but could not find it in the jQuery Mobile GitHub: https://github.com/jquery/jquery-mobile . Thanks for any helps or guidance.
推荐答案
JavaScript最令人兴奋的部分之一是能够使用通常称为冻结允许开发人员阻止此类修改的方法.)
One of the more exciting parts of JavaScript is that ability to redefine any function using a technique which is commonly referred to as Monkey Patching. (as an aside ES5 provides a new freeze method which allows developers to prevent such modifications.)
这是一个JavaScript MonkeyPatch的示例,它使我们无需修改源代码即可修改函数的行为:
Here's an example of a JavaScript MonkeyPatch which allows us to modify the behaviour of a function without editing it's source:
// 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
行,但是我们也可以用猴子来修补它:
Say we wanted to add logging to the sum method, we could just add a console.log
line to the function, but we can also monkey patch it:
// 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
方法:
Now when Example.sum
is called, not only will we get the result as before, but a console message will also be written. With this in mind, you can monkey patch the $.mobile.changePage
method in the same way:
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);
};
这篇关于扩展$ .mobile.changePage接受更多选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!