I have a template:
<template id="item-list">
<form action="" data-bind="submit: addItem">
<input type="text" name="addItem" data-bind="value: newItem">
<button type="submit">Add Item</button>
</form>
<ul class="item-list" data-bind="foreach: items">
<item params="title: title,
$element: $element,
$data: $data,
$parent: $parent"></item>
</ul>
</template>
<template id="item">
<li class="item" data-bind="text: title, click: $parent.removeItem"></li>
</template>
<item-list params="items: items"></item-list>
And a couple of components with some logic:
function Item(title) {
this.title = title
}
ko.components.register('item-list', {
viewModel: function(params) {
this.items = ko.observableArray(params.items)
this.newItem = ko.observable('')
this.addItem = function() {
this.items.push(new Item(this.newItem()))
}
this.removeItem = function(a) {
this.items.remove(a.$data)
}.bind(this)
},
template: {element: 'item-list'}
})
ko.components.register('item', {
viewModel: function(params) {
$.extend(this, params)
},
template: {element: 'item'}
})
function ViewModel() {
this.items = [
new Item('One'),
new Item('Two'),
new Item('Three')
]
}
var vm = new ViewModel()
ko.applyBindings(vm, document.body)
Is there a way to pass the item directly in the foreach
so I don't have to do this?
<ul class="item-list" data-bind="foreach: items">
<item params="title: title,
$element: $element,
$data: $data,
$parent: $parent"></item>
</ul>
But rather something like:
<item params="$context"></item>
I am new to Knockout. I am aware that I could pass an object to the view model and operate on that object, so instead of this.title
I would have to do this.object.title
or this.$data.title
and I would still have to pass $element
and $parent
manually.
Is there any other way to automate this that I am missing?
You can pass the $context
as follows:
<item params="{ context: $context }"></item>
Then in component code:
viewModel: function(params) {
var ctx = params.context;
var itemData = ctx.$data;
$.extend(this, itemData)
},
But, you don't seem to be making use of the context at all, you're only extending this
with the passed item
data. So, the following will do as well:
<item params="{ item: $data }"></item>
viewModel: function(params) {
$.extend(this, params.item)
},
See Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With