Magento2 Knockout.js contentUpdated not binding observables after ajax.

Viewed 1749

I have an issue with observables being fired after content is updated via ajax and javascript is re-initialized via .trigger('contentUpdated'). This all works when the scripts are rendered initially on page load but when they are added via ajax I cannot get the observables to update. For demo purposes I've simplified by logic but basically I have a block that gets loaded via ajax for a product collection like so:

myblock.phtml

<div class="wrapper-id-1">

<!-- this is what gets appended via ajax

    <div id="product-item-<?php echo $productId;?>">
        <span data-bind="text: someObservable()"></span>
        ...
    </div>
   <script type="text/x-magento-init">
   {
       "#product-item-<?php echo $productId;?>": {
       "path/to/component":{
          "some":"vars"
       }
   }
   </script>

<!--and ajax append ends here -->
</div>

In the component that gets bound to the element I have:

component.js

...

this.someObservable: ko.observable('default value'),

 initialize: function () {
    var self = this;
    this.anotherComponentModel().value.subscribe(function(data){
            self.someObservable(data['value']);
        },this);

    },
...

the ajax that calls and loads the collection:

ajaxComponent.js

$.ajax({
    url: 'route/to/controller?cat=' + categoryId,
    success: function (data) {
        $('.wrapper-id-' + categoryId).empty().append('<h2>' + categoryTitle + '</h2>' + data).show().trigger('contentUpdated');
    }
})
...

I see that the component(component.js) gets initialized when contentUpdated is triggered and it has all of the correct data that is needed. However the observables to not fire and the data is not updated to the DOM. This an issue with scope? Or to I need to re-initialize the observables? I tried doing this via not binding directly to the component ie:

<script type="text/x-magento-init">
{
    // components initialized without binding to an element
    "*": {
        "<js_component3>": ...
    }
}
</script>

but it achieves the same result.

What am I missing here.

0 Answers
Related