Вопрос

I wish to set different data-theme attributes depending on the model\object state. Here I'm just setting 'b' or 'd' for the data-theme attribute (jQuery Mobile). I can get it to work with:

<!-- ko if: $data.id() == $parent.selectedMatchId() -->
    <li data-bind="text: $data.date" data-theme="b"></li>
<!-- /ko -->
<!-- ko ifnot: $data.id() == $parent.selectedMatchId() -->
   <li data-bind="text: $data.date" data-theme="d"></li>
<!-- /ko -->

which is a bit ugly. I thought (hoped) I'd be able to use an expression inside the attribute binder, but the Knockout binding engine doesn't like what I give it.

<li data-bind="text: $data.date,
      attr: {'data-theme' : $data.id() == $parent.selectedMatchId() : 'd' ? 'b'}"></li>

Is there a cleaner way to do this than the 'ko if' and 'ko ifnot' that I'm using?

Это было полезно?

Решение

You can use the template binding. With this binding, you can choose dynamically what template to use.

The documentation is here : http://knockoutjs.com/documentation/template-binding.html#note_4_dynamically_choosing_which_template_is_used

Другие советы

I prefer to use a custom binding that changes my jquery mobile theme. For instance, changing the theme of a button based off a true or false observable value to indicate that the button is selected or not:

Custom Binding:

ko.bindingHandlers.jqmButtonTheme = {
    init: function (element, valueAccessor)
    {
        var value = valueAccessor();
        ko.utils.unwrapObservable(value) ? $(element).buttonMarkup({ theme: 'b' }) : $(element).buttonMarkup({ theme: 'a' });
    },
    update: function (element, valueAccessor)
    {
        var value = valueAccessor();
        ko.utils.unwrapObservable(value) ? $(element).buttonMarkup({ theme: 'b' }) : $(element).buttonMarkup({ theme: 'a' });
    }
};

JSFiddle Example:

http://jsfiddle.net/RVLqJ/10/

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top