Coffeescript 'this' inside jQuery .each()
Coffeescript 'this' inside jQuery .each()
我有一些像这样的咖啡脚本:
class foo:
@bar = 'bob loblaw'
processRows: ->
$("#my-table>tr").each ->
id = $(this).attr("id")
@processRow id
processRow: (id) ->
console.log @bar + id
所以我的问题是:我需要this
引用循环内的.each
上下文以获得id
,但我也希望this
引用foo.processRow()
内的类实例-它目前没有这样做。
在.each
函数之外使用_this = this
之类的东西并传递它也不是一个很好的解决方案,因为我在processRow
中引用了许多类变量。
任何想法吗?我错过了什么明显的东西吗?谢谢!
jQuery.each
传递当前元素作为回调的第二个参数,所以你没有为jQuery保留this
:
processRows: ->
$("#my-table>tr").each (index, element) =>
id = $(element).attr("id")
@processRow id
注意使用粗箭头 (=>
)语法回调函数;它将函数的上下文绑定到this
的当前值。(回调函数中的this
始终与您定义该函数时的this
相同)
你说
在
.each
函数之外使用_this = this
之类的东西并传递它也不是一个很好的解决方案,因为我在processRow中引用了许多类变量。
这是最有效的解决方案。JavaScript的this
是一个奇怪的野兽;您可以使用=>
运算符将其固定在嵌套函数中,正如arnaud576875在他的回答中所建议的那样(这是优雅的,但效率低下),或者您可以将this
复制到另一个变量(这是有效的,但不优雅)。选择权在你。
请注意,一些现代浏览器支持每个函数的bind
方法,这比CoffeeScript的=>
更有效。有一个开放的票证让=>
在可用时使用本机bind
: https://github.com/jashkenas/coffee-script/pull/1408
附录:当然,比上述任何一种更有效的替代方法是写
for element, index in $('#my-table>tr')
...
也可以解决你的this
问题
你的代码…
class foo
@bar = 'bob loblaw'
processRows: ->
$("#my-table>tr").each ->
id = $(this).attr("id")
@processRow id
processRow: (id) ->
console.log @bar + id
被编译成…
var foo;
foo = (function() {
function foo() {}
foo.bar = 'bob loblaw';
foo.prototype.processRows = function() {
return $("#my-table>tr").each(function() {
var id;
id = $(this).attr("id");
return this.processRow(id);
});
};
foo.prototype.processRow = function(id) {
return console.log(this.bar + id);
};
return foo;
})();
它假定了它所要翻译的当前上下文。不幸的是,由于jQuery管理上下文,您必须显式地或声明对类的this
的引用。
class foo
@bar = 'bob loblaw'
getBar: () ->
@bar
Transpiles:
var foo;
foo = (function() {
function foo() {}
foo.bar = 'bob loblaw';
foo.prototype.getBar = function() {
return this.bar;
};
return foo;
})();
尝试使用这段代码的结果:
> foo.bar;
"bob loblaw"
> var f = new foo();
undefined
> f.getBar();
undefined
你的代码似乎期望@bar
是一个自己的属性,但它被创建为foo
函数的静态属性
- this内部的值返回this.each(function(){})
- $.each 中的“this”,当需要使用“this”访问对象的函数时
- jQuery插件返回this.each并为每个对象添加函数属性
- this.collection.each不会以这种方式启动(backbone.js)
- jQuery $(selector) 中的“this”.each 函数都引用页面
- 如何在嵌套的 .each()(s) 中正确使用“this”?(JQuery)
- $(this).getAttribute 在使用 $.each XML Javascript 时不是一个函数
- this.something outside each in jquery
- Backbone/Javascript scope.如何在 .each 中访问 this.el
- 为什么当我在单独的函数中使用 $(this) 并在 .each() 中调用它时,它不起作用
- $(this) toggleClass not working with .each?
- "this.collection.each不是函数;.应该'它不是简单地说“;每个”;
- this.key和this[key]之间的差异,使用angularjs for Each
- this.each不是't正在执行
- 如何将jQuery this与.on函数和.each函数一起使用
- 将$(this)传递给jQuery中each()的回调
- jQuery自定义函数- this.each
- 很难让JS使用each和this进行迭代
- jQuery each() 或 (this) 用于显示/隐藏切换
- each() inside function() and $(this)