How to link jQuery Mobile dynamic button set using Knockout.js?

I use jQuery Mobile (jQM) and Knockout.js (ko) to develop the application. In this application, I need to create a variable number of buttons that are determined by a constantly updated web service.

So, in my markup, I have:

<div id="answerPage-buttons" data-bind="foreach: buttonsLabels"> <button data-role="button" data-inline="true" data-theme="b" data-bind="text: text, click: $root.submitAnswer" /> </div> 

buttonLabels is a list of short lines returned by the web service. It is defined as:

 self.buttonLabels = ko.observableArray(); 

All this works great if the buttons are not "jQM style." However, when I style them using:

 $("#answerPage-buttons").trigger("create"); 

There are problems during the upgrade.

The problem seems to be that jQM wraps the buttons in a div (with sibling range) to make them beautiful and mobile. However, when ko applies updates through bindings, it removes only the tags, leaving the surrounding stuff and adds new button tags, which are then also stylized by the jQM trigger call.

So, I get an ever-growing list of buttons - only with the last set valid (since the previous ones were gutted by deleting their button element, but all the styles remained).

I managed to solve this, I think, by the following call immediately after updating the observable:

 $("#answerPage-buttons div.ui-btn").remove(); 

However, I feel that probably the best approach. There is?

+6
source share
1 answer

I have found a solution.

If I surround the buttons with a div, it seems to work - for example,

 <div id="answerPage-buttons" data-bind="foreach: buttonsLabels"> <div> <button data-role="button" data-inline="true" data-theme="b" data-bind="text: text, click: $root.submitAnswer" /> </div> </div> 

I assume this is because the markup added by jQM remains "inside" the markup replicated by ko. Without a div, jQM wraps the button tag, which was the immediate descendant of the tag that contains the ko foreach binding.

+3
source

Source: https://habr.com/ru/post/914670/


All Articles