这是一个简单的视图模型
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);
这是Html
div.span12(data-bind='foreach:cakeBox')
div.row-fluid
div.span4
span(data-bind='text:$data.cakeBox().name()')
这是错误
Uncaught Error: Unable to parse bindings.
Message: TypeError: Object [object Object] has no method 'cakeBox';
Bindings value: text:$data.cakeBox().name()
为什么???
答案 0 :(得分:0)
假设您的HTML看起来像那样:
<div data-bind="foreach:cakeBox">
<span data-bind="text:$data.cakeBox().name()"></span>
</div>
然后你的问题是第二个数据绑定。当您执行foreach
绑定时,该块中的所有绑定都将获取foreach中当前元素的上下文。所以$data
指的是数组中的成员。
它应该是什么样的:
<span data-bind="text:name"></span>
因为name
是当前绑定上下文的属性。
答案 1 :(得分:0)
替换:
data-bind='text:$data.cakeBox().name()
通过
data-bind='text:name'