[英]data-bind didnt work on view model
this is a simple view model 这是一个简单的视图模型
var Cake=function(id,name,price,image)
{
this.id=ko.observable(id);
this.name=ko.observable(name);
this.price=ko.observable(price);
this.image=ko.observable(image);
};
var oldCakes=ko.observableArray(
[
new Cake('HSJ525','Name of the Cake',54.30,'http://placehold.it/160x100'),
new Cake('HSJ526','Other Cake',64.30,'http://placehold.it/160x100'),
new Cake('HSJ527','Another roquefort',84.30,'http://placehold.it/160x100'),
new Cake('HSJ528','AndTheLast',44.30,'http://placehold.it/160x100'),
])
var viewModel=function()
{
var self=this;
self.cakeBox=oldCakes;
}
window.view_model = new viewModel();
ko.applyBindings(window.view_model);
and this is the Html 这是HTML
div.span12(data-bind='foreach:cakeBox')
div.row-fluid
div.span4
span(data-bind='text:$data.cakeBox().name()')
and this is the error 这是错误
Uncaught Error: Unable to parse bindings.
Message: TypeError: Object [object Object] has no method 'cakeBox';
Bindings value: text:$data.cakeBox().name()
why??? 为什么???
Assuming your HTML looks something like this: 假设你的HTML看起来是这样的 :
<div data-bind="foreach:cakeBox">
<span data-bind="text:$data.cakeBox().name()"></span>
</div>
Then your problem is with the second data binding. 然后,您的问题是第二个数据绑定。 When you do a
foreach
binding, all the bindings within that block will get the context of the current element in foreach. 当您执行
foreach
绑定时,该块内的所有绑定都将获取foreach中当前元素的上下文。 So $data
refers to a member in your array. 因此
$data
指向数组中的成员。
What it should look like is: 它应该是什么样的:
<span data-bind="text:name"></span>
Because name
is a property of the current binding context. 因为
name
是当前绑定上下文的属性。
Replace : 更换:
data-bind='text:$data.cakeBox().name()
By 通过
data-bind='text:name'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.