Question

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/

Was it helpful?

Solution

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top