Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding "radio" functionality to buttons when using a custom binder in Rivets.js with Backbone.js

I am using Rivets.js to bind elements to my model. I am using Bootstrap by Twitter for design, and have set up three buttons to choose from the values 1, 2 and 3 (functionally equivalent to radio buttons).

I have set up three buttons in a button group like this:

<div class="btn-group" id="input_level" data-toggle="model.level">
    <button data-toggle-value="1" class="btn active">One</button>
    <button data-toggle-value="2" class="btn">Two</button>
    <button data-toggle-value="3" class="btn">Three</button>
</div>

I have added a custom toggle binder like so:

rivets.binders.toggle = function(el,value){
    $(el).find('button[data-toggle-value="' + value + '"]')
        .addClass('active').siblings().removeClass('active');
}

This updates the button state like it should, but doesn't work the other way - i.e. there is no event bound to the button click event. I want to generalize this to Rivets.js so I don't have to add a click event to each button group in the form in the Backbone view.

Is this basic functionality in Rivets, and if so, how do I set it up?

like image 349
Nils Avatar asked Oct 05 '22 17:10

Nils


1 Answers

After studying the Rivets.js annotated source, I found the solution after a while (I'm not using CoffeeScript, so it was a bit of a hassle to read):

I replaced this piece of original code in my question:

rivets.binders.toggle = function(el,value){
    $(el).find('button[data-toggle-value="' + value + '"]')
        .addClass('active').siblings().removeClass('active');
}

With this:

rivets.binders.toggle = {
    publishes: true,
    bind: function(el){
        $(el).on('click', 'button:not(.active)', _.bind(function(e){
            this.model.set(this.keypath, $(e.currentTarget).data('toggle-value'));
        }, this));
    },
    unbind: function(el){
        $(el).off('click', 'button:not(.active)');
    },
    routine: function(el,value){
        $(el).find('button[data-toggle-value="' + value + '"]')
            .addClass('active').siblings().removeClass('active');
    }
};

The initial code is now under rivets.binders.toggle.routine instead of rivets.binders.toggle.

like image 193
Nils Avatar answered Oct 08 '22 06:10

Nils