admin管理员组文章数量:1404333
I am experimenting a bit with different ways to add methods to knockout viewmodels, and I came across an error I really don't understand.
function ViewModel() {
var self = this;
self.foo = ko.observable(null);
self.hasFoo = koputed(self.getHasFoo);
}
ko.utils.extend(ViewModel.prototype, {
getHasFoo: function () {
return this.foo() != null;
},
});
var vm = new ViewModel();
When I run this, I get an error saying Uncaught TypeError: this.foo is not a function
. I did a console.log on the actual value of this.foo, and it was indeed undefined
. I really don't understand why. What is going on here?
I am experimenting a bit with different ways to add methods to knockout viewmodels, and I came across an error I really don't understand.
function ViewModel() {
var self = this;
self.foo = ko.observable(null);
self.hasFoo = ko.puted(self.getHasFoo);
}
ko.utils.extend(ViewModel.prototype, {
getHasFoo: function () {
return this.foo() != null;
},
});
var vm = new ViewModel();
When I run this, I get an error saying Uncaught TypeError: this.foo is not a function
. I did a console.log on the actual value of this.foo, and it was indeed undefined
. I really don't understand why. What is going on here?
1 Answer
Reset to default 2That's because the context of the puted, this is the syntax ko.puted(handler,scope)
see the update this.hasFoo = ko.puted(self.getHasFoo,this);
, so now see it working in the snippet.
function ViewModel() {
var self = this;
this.foo = ko.observable(null);
this.hasFoo = ko.puted(self.getHasFoo,this);
}
ko.utils.extend(ViewModel.prototype, {
getHasFoo: function () {
return this.foo();
},
});
var vm = new ViewModel();
ko.applyBindings(vm)
<script src="https://cdnjs.cloudflare./ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="text" data-bind="textInput: foo"/>
<span data-bind="visible: hasFoo"> Has FOO!! </span>
Managing ‘this’
The second parameter to ko.puted (the bit where we passed this in the above example) defines the value of this when evaluating the puted observable. Without passing it in, it would not have been possible to refer to this.firstName() or this.lastName(). Experienced JavaScript coders will regard this as obvious, but if you’re still getting to know JavaScript it might seem strange. (Languages like C# and Java never expect the programmer to set a value for this, but JavaScript does, because its functions themselves aren’t part of any object by default.)
Ref. KO puted observables
本文标签: javascriptknockout observable is not a functionStack Overflow
版权声明:本文标题:javascript - knockout observable is not a function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744790733a2625271.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论