Cia*_*her 13 javascript oop jquery design-patterns prototypejs
我来自Prototype JS背景,其中通过使用来鼓励OO Javascript Class.create().现在我正在做一些JQuery工作,我正在尝试编写一些结构合理的JQuery代码,例如,我可以从两个不同的单击事件处理程序调用相同的对象函数.
这是Prototype中的代码:
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!
}
});
Run Code Online (Sandbox Code Playgroud)
我想知道如何在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 )
Run Code Online (Sandbox Code Playgroud)
此方法对于将事件处理程序附加到上下文指向不同对象的元素最有用。此外,jQuery 确保即使您绑定从 jQuery.proxy() 返回的函数,如果传递了原始函数,它仍然会取消绑定正确的函数。
| 归档时间: |
|
| 查看次数: |
7059 次 |
| 最近记录: |