jQuery中的$.proxy官方描述为:

描述:接受一个函数,然后返回一个新函数,并且这个新函数始终保持了特定的上下文语境。

官方API;

jQuery.proxy( function, context )

function为执行的函数,content为函数的上下文this值会被设置成这个object对象

jQuery.proxy( context, name )

content 函数的上下文会被设置成这个object对象,name要执行的函数,次函数必须是content对象的属性、

jQuery.proxy( function, context [, additionalArguments ] )

function为执行的函数,content为函数的上下文this值会被设置成这个object对象,additionalArguments任何数目的参数,传递给function

更详细的用法参考:

http://www.css88.com/jqapi-1.9/jQuery.proxy/

现在让我们一起来看实际例子:

  1. var objPerson = {
  2. name: "obj",
  3. age: 32,
  4. test: function() {
  5. $("p").after("Name: " + this.name + "<br> Age: " + this.age);
  6. }
  7. }
  8.  
  9. $("#btn").on("click", $.proxy(objPerson.test, objPerson))

点击按钮,输出:Name:obj  Age:32

objPerson.test表示上下文的方法,objPerson代表执行的上下文,例子中的this的上下文指的是objPerson

更具体的例子如:

  1. var me = {
  2. type: "zombie",
  3. test: function(event) {
  4. /* Without proxy, `this` would refer to the event target */
  5. /* use event.target to reference that element. */
  6. var element = event.target;
  7. $(element).css("background-color", "red");
  8.  
  9. /* With proxy, `this` refers to the me object encapsulating */
  10. /* this function. */
  11. $("#log").append("Hello " + this.type + "<br>");
  12. $("#test").unbind("click", this.test);
  13. }
  14. };
  15.  
  16. var you = {
  17. type: "person",
  18. test: function(event) {
  19. $("#log").append(this.type + " ");
  20. }
  21. };
  22.  
  23. /* execute you.test() in the context of the `you` object */
  24. /* no matter where it is called */
  25. /* i.e. the `this` keyword will refer to `you` */
  26. var youClick = $.proxy(you.test, you);
  27.  
  28. /* attach click handlers to #test */
  29. $("#test")
  30.  
  31. /* this === "zombie"; handler unbound after first click */
  32. .on("click", $.proxy(me.test, me))
  33.  
  34. /* this === "person" */
  35. .on("click", youClick)
  36.  
  37. /* this === "zombie" */
  38. .on("click", $.proxy(you.test, me))
  39.  
  40. /* this === "<button> element" */
  41. .on("click", you.test);

结合以上说明,再写一个综合的例子,例如 js封装一个ajax请求,代码如下:

  1. var t = {
  2. param: {},
  3. url: "",
  4. type: "get",
  5. dataType: "json",
  6. ajaxOnly: true,
  7. contentType: 'application/x-www-form-urlencoded',
  8. /**
  9. * 取model数据
  10. * @param {Function} onComplete 取完的回调函
  11. * 传入的第一个参数为model的数第二个数据为元数据,元数据为ajax下发时的ServerCode,Message等数
  12. * @param {Function} onError 发生错误时的回调
  13. * @param {Boolean} ajaxOnly 可选,默认为false当为true时只使用ajax调取数据
  14. * @param {Boolean} scope 可选,设定回调函数this指向的对象
  15. * @param {Function} onAbort 可选,但取消时会调用的函数
  16. */
  17. execute: function(onComplete, onError, ajaxOnly, scope) {
  18. var __onComplete = $.proxy(function(data) {
  19. var _data = data;
  20. if (typeof data == 'string') _data = JSON.parse(data);
  21.  
  22. // @description 对获取的数据做字段映射
  23. var datamodel = typeof this.dataformat === 'function' ? this.dataformat(_data) : _data;
  24.  
  25. if (this.onDataSuccess) this.onDataSuccess.call(this, datamodel, data);
  26. if (typeof onComplete === 'function') {
  27. onComplete.call(scope || this, datamodel, data);
  28. }
  29.  
  30. }, this);
  31.  
  32. var __onError = $.proxy(function(e) {
  33. if (typeof onError === 'function') {
  34. onError.call(scope || this, e);
  35. }
  36. }, this);
  37.  
  38. this.sendRequest(__onComplete, __onError);
  39.  
  40. },
  41.  
  42. sendRequest: function(success, error) {
  43. var params = _.clone(this.getParam() || {});
  44. var crossDomain = {
  45. 'json': true,
  46. 'jsonp': true
  47. };
  48.  
  49. if (this.type == 'POST') {
  50. this.dataType = 'json';
  51. }
  52.  
  53. //jsonp与post互斥
  54. $.ajax({
  55. url: this.url,
  56. type: this.type,
  57. data: params,
  58. dataType: this.dataType,
  59. contentType: this.contentType,
  60. crossDomain: crossDomain[this.dataType],
  61. timeout: 50000,
  62. // xhrFields: {
  63. // withCredentials: true
  64. // },
  65. success: function(res) {
  66. success && success(res);
  67. },
  68. error: function(err) {
  69. error && error(err);
  70. }
  71. });
  72. },
  73.  
  74. setParam: function(key, val) {
  75. if (typeof key === 'object') {
  76. _.extend(this.param, key);
  77. } else {
  78. this.param[key] = val;
  79. }
  80. },
  81.  
  82. removeParam: function(key) {
  83. delete this.param[key];
  84. },
  85.  
  86. getParam: function() {
  87. return this.param;
  88. },
  89.  
  90. dataformat: function(data) {
  91. if (_.isString(data)) data = JSON.parse(data);
  92. if (data.data) return data.data;
  93. return data;
  94. },
  95.  
  96. onDataSuccess: function() {}
  97. }

调用封装的方法:

  1. function getData(url) {
  2. //设置参数
  3. t.setParam({
  4. "CurrentDestId": 7,
  5. "Platform":2,
  6. "ViewDestId":7
  7. });
  8. t.url=url;
  9. t.type="post";
  10.  
  11. //调用
  12. t.execute(function(data){
  13. var list=data.Tags;
  14. var temp=_.template($("#foodListTemp").html());
  15. $("#list").html(temp({"dataTag":list}));
  16. },function(data){
  17. alert("fail");
  18. });
  19. }

随机推荐

  1. 第二次去苹果店维修MacBook

    今天上午,在使用外接鼠标的情况下,屏幕上鼠标指针乱窜.乱点.不受控制的故障再次出现,这次拍下了视频. 再次去苹果网站预约Genius Bar(天才吧),中午的时候去了苹果店.这次没有像上次那样检查身份 ...

  2. 使用pidstat查看进程资源使用情况

    简介 pidstat主要用于监控全部或指定进程占用系统资源的情况,如CPU,内存.设备IO.任务切换.线程等.pidstat首次运行时显示自系统启动开始的各项统计信息,之后运行pidstat将显示自上 ...

  3. Grafana+Prometheus监控

    添加模板一定要看说明以及依赖 监控redis https://blog.52itstyle.com/archives/2049/ http://www.cnblogs.com/sfnz/p/65669 ...

  4. find the safest road---hdu1596(最短路模板求最大概率)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1596 求给定的任意两点之间的最大安全概率,概率之间是相乘的关系,所以注意初始化即可 #include& ...

  5. hive引入jar包--HIVE.AUX.JARS.PATH和hive.aux.jars.path

    hive需要引入包时?该怎么引入? 一.hive-site.xml中的hive.aux.jars.path 此配置项对于hive server有效,但是是不会作用到hive shell.也就是说即使你 ...

  6. 使用celery之了解celery(转)

    原文  http://www.dongwm.com/archives/shi-yong-celeryzhi-liao-jie-celery/   前言 我想很多做开发和运维的都会涉及一件事:cront ...

  7. pandas 取消读取csv时默认第一行为列名

    读取时默认第一行为列名 此时DataFrame的列名为第一行数据: 因为第一行为有效数据,故不可作为列名,要么重新起列名,要么使用默认序列列名: 取消默认第一行为列名 给 pd.read_csv() ...

  8. MySQL的知识海洋

    第一篇:初识数据库 第二篇:库操作 第三篇:表操作 第四篇:数据操作 第五篇:视图.触发器.存储过程.函数.事物与数据库锁 第六篇:索引原理与慢查询优化 第七篇:pymysql(用python连接以及 ...

  9. js-jquery-SweetAlert2【二】配置与方法

    一.配置 Argument Default value   Description title null 模态对话框的标题.它可以在参数对象的title参数中设置,也可以在swal()方法的第一个参数 ...

  10. [随感]GIS开发的困惑

    从事GIS应用开发也有3年了,但是做了些东西自己始终不满意,不是不稳定就是效率低,不是功能杂就是不实用! 首先是AE开发,我必须说自己很欣赏ArcGIS的软件设计架构和思想.但是在开发的过程中也确实遇 ...