I have this dropdown which have options if vehicle is new or used.
If you're using the ko mapping plugin you can intercept the creation of a new object and set up the subscription there. If you have a whole list of items and you want to perform an action when something changes.
This is a view model for a shopping cart line item (properties such as qty
, sku
, description
, price
).
// View Model for an item in my shopping cart
var CartItemViewModel = function(data)
{
// map all the properties
// we could map manually if we want, but that's the whole point of
// the mapping plugin that we don't need to
ko.mapping.fromJS(data, {}, this);
// subscribe to qty change
this.qty.subscribe(function (newValue)
{
alert('qty now ' + this.qty());
// UpdateCart()
}, this);
// add computed observables if needed
// ....
}
When you update (or create) your model using the mapping plugin you specify that for a property called 'items' each element in the array should be created with the 'create' function you specify.
var mapping =
{
'items':
{
// map cart item
create: function (options)
{
return new CartItemViewModel(options.data);
}
}
};
var data = ...... // get your data from somewhere
// update the CartViewModel using the mapping rules
ko.mapping.fromJS(data, mapping, rrvm.CartViewModel);