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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With