KnockoutJS access active item created via activator forItems

112 Views Asked by At

As per the Master-detail samples, such as this, but with factory pattern for viewmodels:

this.activateProduct = activator.create().forItems(this.products);

<div data-bind="foreach: products">
   <a data-bind="click: $parent.activateProduct">click activates</a>`
</div>

Debugging <pre data-bind="text: ko.toJSON(activateProduct, null, 2)"></pre> outputs the model and it's data.

However <div data-bind="text: activateProduct.name"></div> returns nothing, tried unwrapping, calling as valueAssessor function etc and can't find the observables which ko.toJSON has somehow found.

Does this all have to be broken down into separate steps using activateItem while storing the "current item"?

Any syntax which will retrieve the observables inside?

1

There are 1 best solutions below

5
On BEST ANSWER

Found it!

ko.unwrap(activateProduct).name()

Problem is that ko.unwrap(activateProduct) == null until it is activated by the click. Thus setting it simply to that will result in a binding error.

Unable to process binding "text: function (){return ko.unwrap(activateProduct).name() }"
Message: ko.unwrap(...) is null;

Thus you must first check for a null value for the activator before attempting to bind it's observables.

<div data-bind="text: (ko.unwrap(activateProduct) !== null) ? ko.unwrap(activateProduct).name():''"></div>