Craig
Craig

Reputation: 18734

Knockout and a toggle switch - data-bind

I am switching from javascript, to Knockout. On my page, I use a BootStrap toggle switch.

http://www.bootstraptoggle.com/

Before, I would set a div as visible based on the value of the switch like this:

if($("#HasPromotion").bootstrapSwitch('state') == false)
{
    $("#promotiondiv").hide();
}

And my control was defined as :

@Html.CheckBoxFor(x => x.HasPromotion, new { @class = "toggleswitchcontrol", data_on_text = "Yes", data_off_text = "No" })

With knockout, I want to databind the value to a property on my viewmodel.

I am trying this:

<input type="checkbox" class="toggleswitchcontrol" data-on-text="Yes" data-off-text="Nope" data-bind="attr: {state: hasPromotion}" />

No success.... I'm not sure what property to bind. How can I bind the control to that property in my view model?

Upvotes: 0

Views: 1485

Answers (1)

Bryan Dellinger
Bryan Dellinger

Reputation: 5304

sorry did not realize you were using a different boostrap switch than the one in my comment. I updated the fiddle to add a custom binding for boostraptoggle.
http://jsfiddle.net/MBLP9/356/

here is the binding.

ko.bindingHandlers.bootstrapToggleOn = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        $elem = $(element);
        $(element).bootstrapToggle();
        if (ko.utils.unwrapObservable(valueAccessor())){
          $elem.bootstrapToggle('on')
        }else{
           $elem.bootstrapToggle('off')
        }

      $elem.change(function() {
       if ($(this).prop('checked')){
          valueAccessor()(true);
       }else{
           valueAccessor()(false);
       }
    })

    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var vStatus = $(element).prop('checked');
        var vmStatus = ko.utils.unwrapObservable(valueAccessor());
        if (vStatus != vmStatus) {
            $(element).bootstrapToggle('toggle')
        }
    }
};

Upvotes: 1

Related Questions