0
votes

I am new to Backbone and would like some help with best practices. Here is a simplified version of my question:

I have several buttons in a form, each of which has its own Backbone Model and View. On Click, I would like some input field (outside the scope of these buttons) to be populated with that button's value.

I want to write this in a reusable way, so I would rather not define an event handler which simply calls $("input").val(...);. I am also not a huge fan of firing/listening for custom events.

The solution I have developed is passing a function in the options hash which is ultimately called by the View's event handler. Is there a better way? thanks!

fiddle: http://jsfiddle.net/pmn4/XW955/

1
I guess this is more of a matter of taste than best practice. I would have given the buttons the same custom class name, then using delegateEvents in the ButtonsListView, attached a click handler to that class. The handler just reads a data- attribute on the button to determine the value to populate the input with. The avantage of delegateEvents in render() is that you can properly clean the event handlersBruno Grieder

1 Answers

1
votes

Backbone is event-driven library so it is best practice to use events to make parts of application less coupled. So you can trigger event on your view when some button is clicked and listen to it in some kind of controller/mediator - object that know about peaces of your application and can change input when button is clicked.

var ButtonSetController = _.extend({
    start: function(){
        var buttonSetCollection = new ButtonList([{val: "A"}, {val: "B"}, {val: "C"}]),
            buttonSetView = new ButtonListView({collection: buttonSetCollection});

        this.listenTo(buttonSetView, "button:clicked", this.onButtonClicked);

        $("form").append(buttonSetView.render().el);  
    },
    onButtonClicked: function(button){
        $("input").val(button.get("val"));
    },
    stop: function(){
        this.stopListening();
    }
}, Backbone.Events);

ButtonSetController.start();

Here is code: http://jsfiddle.net/8aY3M/