jQuery   发布时间:2022-04-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了用jQuery写OO Javascript大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我来自一个Prototype JS背景,通过使用Class.create()鼓励OO Javascript.现在我正在做一些JQuery的工作,我正在尝试编写一些正确结构化的JQuery代码,我可以从这两个不同的click事件处理程序中调用相同的对象函数.

以下是原型中的代码

document.observe("dom:loaded",function() {

    // create document
    APP.pageHelper = new APP.pageHelper();


});

// namespace our code
window.APP = {};

// my class
APP.pageHelper = Class.create({

  // automatically called
  initialize: function(name,sound) {
    this.myValue = "Foo";

    // attach event handlers,binding to 'this' object
    $("myButton").observe("click",this.displaymessage.bind(this))

  },displaymessage: function() {
    console.log("My value: " + this.myvalue); // 'this' is the object not the clicked button!
  }

});@H_675_5@ 
 

我想知道如何在JQuery中如何复制以下代码,其中没有办法将函数调用绑定到调用的对象中,“this”始终是单击的元素.

听说有道理的道格拉斯·克罗克福德’模块’模式(http://www.yuiblog.com/blog/2007/06/12/module-pattern/),但是如果有人能告诉我如何您将使用JQuery和该模式实现上述代码.

提前致谢.

解决方法

您可以将事件绝对绑定到dom元素之外的东西.只需使用$.proxy.

描述:

执行一个函数并返一个总是具有特定上下文的新函数.
版本增加:1.4

/**
  * @param function - The function whose context will be changed.
  * @param context - The object to which the context (this) of the function should be set.
  */
jQuery.proxy( function,context )@H_675_5@ 
 

方法对于将事件处理程序附加到上下文指向不同对象的元素最为有用.另外,jQuery确保即使绑定从jQuery.proxy()返回的函数,它仍然会解除绑定正确的功能,如果传递原始.

大佬总结

以上是大佬教程为你收集整理的用jQuery写OO Javascript全部内容,希望文章能够帮你解决用jQuery写OO Javascript所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。