简体   繁体   中英

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

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:

<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. So $data refers to a member in your array.

What it should look like is:

<span data-bind="text:name"></span>

Because name is a property of the current binding context.

Replace :

 data-bind='text:$data.cakeBox().name()

By

data-bind='text:name'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM