使用 jQuery 编写 OO Javascript

2024-03-27

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

这是原型中的代码:

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”始终是单击的元素。

我听说过一种方法,可以使用 Douglas Crockford“模块”模式(http://www.yuiblog.com/blog/2007/06/12/module-pattern/),但如果有人能告诉我如何做,我会很高兴您可以使用 JQuery 和该模式来实现上面的代码。

提前致谢。


我根据这篇好文章滚动我自己的对象:

http://www.klauskomenda.com/code/javascript-programming-patterns/ http://www.klauskomenda.com/code/javascript-programming-patterns/

我只是选择对我正在从事的项目有意义的模式。因此,就像执行您所要求的操作的一个快速示例一样:

$.myNamespace.myClass = function (options) {
    this.settings = $.extend({ ... defaults ... }, options);
    this.init();
};
$.myNamespace.myClass.prototype.settings = {
    someValue: 'default',
    someSelector: '#myButton'
};
$.myNamespace.myClass.prototype.init = function () {
    var self = this;
    $(self.settings.someSelector).click(function (event) {
        console.log(self.settings.someValue);
    });
};

您在下面回复说您了解原型,但语法有点烦人。我认为这只是习惯一种语法而不是另一种语法的问题。我确信 Prototype 库会使用闭包和 .prototype 就像我上面所做的那样以及下面建议的其他一些答案。最后,只需编写您觉得舒服的语法即可。使用 Coffee Script 的建议也很酷 - 任何能让你的船漂浮的东西:)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 jQuery 编写 OO Javascript 的相关文章

随机推荐