I have a project where I cannot figure out how to access the observableArray from a click event as called from the container template. I have a stripped down example in a fiddle here:
The click event is specified in a template which then dynamically loads a template for each item from a property on the item itself.
So an example item is:
{ID: 1, TemplateName: 'template1', Label: 'Name', Description: 'Your name'}
The “parent” template looks like this:
<script type="text/html" id="tpl-placeholder">
<div class="entry" data-bind="click: $parent.RemoveEntry, attr: { id: ID}, template: {name: TemplateName }"></div>
</script>
And a dynamically loaded template looks like this:
<script type="text/html" id="template1">
<h1 data-bind="text: Label"></h1>
<div data-bind="text: Description"></div>
</script>
In the method that handles the click event – in this case, RemoveEntry – I get null when trying to access the observableArray (Entries).
Here is the viewmodel:
var viewModel = {
Name: ko.observable("Entries"),
Entries: ko.observableArray( entries ),
RemoveEntry: function (entry) {
// how do I access the "Entries" list here - this.Entries returns null
$("#debug").text(this.Entries == null);
this.Entries.remove(entry);
}
};
I am a knockout newb .. can someone tell me what am I doing wrong here?
Thanks!
the way you have it, you directly access viewmodel.Entries…
however, more typically you’d do it like :-
http://jsfiddle.net/keith_nicholas/RAMcc/
with the good ol javascript hack