admin 管理员组文章数量: 1086019
I have created a Javascript namespace to avoid conflict with other Javascript codes.
var ns = {
init: function() {
$('a').click(this.clickHandler);
},
clickHandler: function() {
// Some code here ..
// The keyword "this" does not reference my "ns" object anymore.
// Now, it represents the "anchor"
this.updateUI();
},
updateUI: function() {
// Some code here ...
}
};
Please, how can I reference my enclosing namespace?
I have created a Javascript namespace to avoid conflict with other Javascript codes.
var ns = {
init: function() {
$('a').click(this.clickHandler);
},
clickHandler: function() {
// Some code here ..
// The keyword "this" does not reference my "ns" object anymore.
// Now, it represents the "anchor"
this.updateUI();
},
updateUI: function() {
// Some code here ...
}
};
Please, how can I reference my enclosing namespace?
Share Improve this question asked Jun 19, 2013 at 15:57 AmmarAmmar 2,4371 gold badge15 silver badges12 bronze badges 04 Answers
Reset to default 6$.proxy
$('a').click($.proxy(this.clickHandler, this));
You can bind event handler to an anonymous function and call clickHandler within it. This way the context will still refer to ns object.
var ns = {
init: function() {
var self = this; // store context in closure chain
$('a').click(function () {
self.clickHandler();
});
},
clickHandler: function() {
this.updateUI();
},
updateUI: function() {
// Some code here ...
}
};
Here is an article: http://www.codeproject./Articles/108786/Encapsulation-in-JavaScript
It explains to create a closure in the namespace where you can store stuff (like the original 'this')
var ns = (function () {
var self;
return {
init: function () {
self = this;
$('a').click(this.clickHandler);
},
clickHandler: function () {
// Some code here ..
self.updateUI();
},
updateUI: function () {
// Some code here ...
}
};
})();
FIDDLE HERE
A good way to do that is to define a local variable in a function that refers to it. This helps when "this" changes on you. Your code could look something like this:
var ns = new (function() {
var self = this;
self.init = function() {
$('a').click(self.clickHandler);
},
self.clickHandler = function() {
// Some code here ..
// The keyword "this" does not reference my "ns" object anymore.
// Now, it represents the "anchor"
self.updateUI();
},
self.updateUI = function() {
// Some code here ...
}
})();
This allows you to still reference the event handler with this and then reference your namespace with the locally defined reference that is only available from within.
本文标签: JavaScript Namespace amp jQuery Event HandlerStack Overflow
版权声明:本文标题:JavaScript Namespace & jQuery Event Handler - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744033004a2521850.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论