CoffeeScript + KnockoutJS 函数绑定
我正在使用 CoffeeScript 和 KnockoutJS,但在从函数内获取视图模型的值时遇到问题。
我有一个视图模型:
window.Application || = {}
class Application.ViewModel
thisRef = this
searchTerm: ko.observable("")
search: ->
alert @searchTerm
编译为:
window.Application || (window.Application = {});
Application.ViewModel = (function() {
var thisRef;
function ViewModel() {}
thisRef = ViewModel;
ViewModel.prototype.searchTerm = ko.observable("");
ViewModel.prototype.search = function() {
return alert(this.searchTerm);
};
return ViewModel;
})();
该视图模型是父视图模型的一部分,它将其公开为字段。问题是我无法获得对子视图模型的引用。在搜索函数中,“this”是父级的实例,这是我不想要的。
I'm using CoffeeScript and KnockoutJS and have a problem getting the values of my view model from within a function.
I have a view model:
window.Application || = {}
class Application.ViewModel
thisRef = this
searchTerm: ko.observable("")
search: ->
alert @searchTerm
Which compiles to:
window.Application || (window.Application = {});
Application.ViewModel = (function() {
var thisRef;
function ViewModel() {}
thisRef = ViewModel;
ViewModel.prototype.searchTerm = ko.observable("");
ViewModel.prototype.search = function() {
return alert(this.searchTerm);
};
return ViewModel;
})();
This view model is part of a parent view model which exposes it as field. The problem is that I can't get a reference to the child view model. In the search function 'this' is a instance of the parent, which I don't want.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这取决于您如何调用它。如果你
这样做,那么
this
将是m
;如果你这样写,那么
this
将是obj
。无论如何,只需使用 CoffeeScript 的
=>
运算符即可:这样,
search
中的this
/@
将指向ViewModel
实例。正如 Travis 所说,thisRef 将仅指向类,而不是实例。
That depends on how you call it. If you do
then
this
will bem
; if you writethen
this
will beobj
.Anyway, just use CoffeeScript's
=>
operator:That way,
this
/@
withinsearch
will point to theViewModel
instance.thisRef
will, as Travis says, just point to the class, not the instance.您已经有一个
thisRef
对象,请使用thisRef.searchTerm
而不是@searchTerm
。我在使用 jQuery 时经常遇到这种情况...因为
@doSomethingElse()
将绑定到执行单击的 DOM 元素。不是我想要的。You already have a
thisRef
object hanging around, usethisRef.searchTerm
instead of@searchTerm
. I often have that happen when using jQuery...Since
@doSomethingElse()
would be bound to the DOM element the click was executed for. Not what I want.