[英]knockout observable array computed
I am trying to implement a simple 'toString' function for an observableArray
.我正在尝试为
observableArray
实现一个简单的“toString”函数。
When using this code which seems the most appropriate to me当使用这个对我来说最合适的代码时
var viewModel = {
name: ko.observable('test'),
arr: ko.observableArray(['item1']),
third: ko.computed(function(){
return this.arr().join();
})
};
ko.applyBindings(viewModel);
I get a this.arr is not a function error我得到一个 this.arr is not a function错误
Why is this happening?为什么会这样?
If I run it like this everything is ok.如果我这样运行它一切正常。
var viewModel = {
name: ko.observable('test'),
arr: ko.observableArray(['item1']),
third: function(){
return this.arr().join();
}
};
ko.applyBindings(viewModel);
If I use the second approach, will I get the correct arr contents?如果我使用第二种方法,我会得到正确的 arr 内容吗? Does the third variable get updated every time an item is added/removed from arr?
每次从 arr 添加/删除项目时,第三个变量是否都会更新?
https://jsfiddle.net/zek2kz2b/5/ https://jsfiddle.net/zek2kz2b/5/
What's happening is that this
in your computed isn't the view model so it doesn't have an arr
method.发生的事情是您的计算中的
this
不是视图模型,因此它没有arr
方法。
You need to provide your computed with the this
context to use when it's invoked.您需要为您的计算提供
this
上下文以在调用时使用。 You can do this by passing the view model a second parameter in your ko.computed
call.您可以通过在
ko.computed
调用中向视图模型传递第二个参数来实现此ko.computed
。
But because you're creating your view model as a plain object, you don't have the view model to pass in at the time you're calling ko.computed
.但是因为您将视图模型创建为一个普通对象,所以您在调用
ko.computed
时没有要传入的视图模型。 So create your view model as a constructor function instead:因此,将您的视图模型创建为构造函数:
function ViewModel() {
var self = this; // Capture the view model as self to simplify things
self.name = ko.observable('test'),
self.arr = ko.observableArray(['item1']),
self.third = ko.computed(function(){
return this.arr().join();
}, self); // We now have the view model available to pass here
};
ko.applyBindings(new ViewModel());
Another way to do this is to simply reference the self
reference to the view model in the computed:另一种方法是简单地将
self
引用引用到计算中的视图模型:
function ViewModel() {
var self = this;
self.name = ko.observable('test'),
self.arr = ko.observableArray(['item1']),
self.third = ko.computed(function(){
return self.arr().join();
});
};
ko.applyBindings(new ViewModel());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.