Reputation: 6271
I have a list of people and each person has a list of pets. I would like to get the list of people on page load. I only want to load a list of one persons pets if the users clicks view pets
here is the jsfiddle uses coffeescript
http://jsfiddle.net/eiu165/rScSL/15/
the getPets seems to be called over and over just when loading
<a href="#" data-bind="click: $root.getPets()">view pets</a>
EDIT
I have figured it out by adding methods to the Person object directly.
http://jsfiddle.net/eiu165/rScSL/22/
Upvotes: 0
Views: 109
Reputation: 6271
I had no idea i could add methods to the Person class
I added the getPets Method in Person in order to get my own list of pets
Person = (data) ->
name = ko.observable(data.name)
lname = ko.observable(data.lname)
pets = ko.observableArray(data.pets)
getPets = (person) ->
data = '{"pets":[
{"age": "5", "type": "dog"},
{"age": "4", "type": "cat"}
]}'
json = $.parseJSON(data).pets
mappedItems = $.map(json , (i)-> Pet(i) )
pets(mappedItems)
name:name
lname:lname
pets:pets
getPets:getPets
http://jsfiddle.net/eiu165/rScSL/21/
Upvotes: 0
Reputation: 114792
When you use the click
binding (or event
binding), you want to bind it against a reference to a function and not the actual invocation of it.
So, you would just want to do:
<a href="#" data-bind="click: $root.getPets">view pets</a>
Otherwise, the code is actually getting executed. You would likely not want to do this unless the function returns the actual function that you want to use.
Upvotes: 3