用jQuery写OO Javascript [英] Writing OO Javascript with jQuery

查看:111
本文介绍了用jQuery写OO Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自一个Prototype JS背景,通过使用 Class.create()鼓励OO Javascript。现在我正在做一些JQuery的工作,我正在尝试编写一些正确结构化的JQuery代码,我可以从这两个不同的click事件处理程序中调用相同的对象函数。

I come from a Prototype JS background where OO Javascript is encouraged through the use of Class.create(). Now I am doing some JQuery work and I am trying to write some properly structured JQuery code where I can, for example, call the same object function from two different click event handlers.

以下是原型中的代码:

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!
  }

});

我想知道如何在JQuery中复制以下代码,其中无法绑定函数调用它所调用的对象,this始终是单击的元素。

I am wondering how the following code can be replicated in JQuery where there is no way to bind a function call to the object it is called in, and 'this' is always the element clicked.

我听说过道格拉斯Crockford'模块'模式(http://www.yuiblog.com/blog/2007/06/12/) module-pattern /),但是如果有人能告诉我如何使用JQuery和该模式来实现上面的代码,我会很乐意。

I have heard of a way to do it the Douglas Crockford 'module' pattern (http://www.yuiblog.com/blog/2007/06/12/module-pattern/) but I would love if someone could show me how you would implement the code above using JQuery and that pattern.

提前感谢。

推荐答案

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

You can absolutely bind an event to something other then the dom element. Just use $.proxy.

获取一个函数并返回一个总是具有特定上下文的新函数。
版本添加:1.4

Takes a function and returns a new one that will always have a particular context. version added: 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 )

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

This method is most useful for attaching event handlers to an element where the context is pointing back to a different object. Additionally, jQuery makes sure that even if you bind the function returned from jQuery.proxy() it will still unbind the correct function if passed the original.

这篇关于用jQuery写OO Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆