我这里有一些代码:
App.prototype.binds = function(){ var that = this; $('.postlist li').live('click', function(){ that.selectPost(this);} ); } App.prototype.selectPost = function(){ this.function(); }我在我的binds函数中创建了“this”的引用,因此在我的selectPost()中,我可以使用“this”来引用App对象而不是列表项。
是否有更优雅/标准的解决方案,而不是使用“那”?
通过答案,我的代码变为:
App.prototype.binds = function(){ $('.postlist li').live('click', $.proxy(this.selectPost, this) ); } App.prototype.selectPost = function(e){ this.function(); // function in App var itemClicked = e.currentTarget; //or var $itemClicked = $(e.currentTarget); }I have some code here:
App.prototype.binds = function(){ var that = this; $('.postlist li').live('click', function(){ that.selectPost(this);} ); } App.prototype.selectPost = function(){ this.function(); }I am creating a reference of "this" as "that" in my binds function so in my selectPost(), I can use "this" to reference the App object instead of the list item.
Is there a more graceful/standard solution to this instead of using "that"?
With the Answer, my code becomes:
App.prototype.binds = function(){ $('.postlist li').live('click', $.proxy(this.selectPost, this) ); } App.prototype.selectPost = function(e){ this.function(); // function in App var itemClicked = e.currentTarget; //or var $itemClicked = $(e.currentTarget); }最满意答案
您可以在构造函数中或正好绑定函数:
在构造函数中
function App() { this.selectPost = this.selectPost.bind( this ); //$.proxy( this.selectPost, this ) in jQuery } App.prototype.binds = function(){ $('.postlist li').live('click', this.selectPost ); //Already bound in constructor }及时:
App.prototype.binds = function(){ $('.postlist li').live('click', this.selectPost.bind( this )); //$.proxy( this.selectPost, this ) in jQuery }请注意, .bind仅在较新的浏览器中受支持,jQuery具有$.proxy ,应该是首选。
我已经在jQuery中打开了一个已被接受的功能请求http://bugs.jquery.com/ticket/12031 。 使用jQuery事件时,这将使这更容易。
请注意,在jQuery事件处理程序中, e.target与正常this相同,这是一个常见的误解。 它实际上是e.currentTarget 。 所以既然this是指实例而不是元素,你可以通过e.currentTarget获取e.currentTarget 。
You can bind the functions in constructor or just in time:
In constructor
function App() { this.selectPost = this.selectPost.bind( this ); //$.proxy( this.selectPost, this ) in jQuery } App.prototype.binds = function(){ $('.postlist li').live('click', this.selectPost ); //Already bound in constructor }Just in time:
App.prototype.binds = function(){ $('.postlist li').live('click', this.selectPost.bind( this )); //$.proxy( this.selectPost, this ) in jQuery }Note that .bind is only supported in newer browsers, jQuery has $.proxy that should be preferred.
I have opened a feature request in jQuery that has been accepted http://bugs.jquery.com/ticket/12031. It will make this easier when using jQuery events.
Note that there is a common misunderstanding that the e.target will be same as normal this in a jQuery event handler. It is actually e.currentTarget. So now that this refers to the instance and not the element, you can get the elemet through e.currentTarget.
更多推荐
发布评论