Damian U Damian U - 1 year ago 49
Javascript Question

Should I put events binding in controller or view?

I want to ask you where to put events binding in mvc app. I'm using javascript and requirejs.

This is ProductsListView modul which renders list in html.

define([ 'jquery' ], function($) {

function render(products, productClickEvent) {
var list = $('#productsPanel ol');

products.forEach(function(item) {
var li = $('<li></li>').text(item.name).appendTo(list);

return {
render : render

My controller 'ProductsListController' looks like this:

define(['app/services/ProductsAjax', 'app/views/ProductsListView'],function(ProductsAjax, productsListView) {

function renderProducts(products) {

return {

loadProducts : function() {


Where I should put events binding for list elements?
I have solution to add events binding in ProductsListView where is created list by just append click event to list element.

var li = $('<li></li>').text(item.name).click(function() {


Answer Source

I would use two different bindings. One listening to the DOM click and one listening to a more abstract event generated from the DOM click.

I would bind to the DOM click event in the view. It is the view which knows how it is structured and what it should listen to to know that a user has selected a product. You could change the view to display products using a different structure. A tree instead of a list, for instance. Then the binding would have to be done differently. The view should be responsible for doing the binding to the DOM in a way consistent with the structure it uses. This keeps concerns separated.

The event handler in the view for the DOM click event should then generate a more abstract event indicating "the user selected product X." Generating an abstract event from the concrete DOM click allows you to have multiple ways to select a product without the rest of your application having to worry exactly how it was selected. If you add support for key shortcuts, for instance, you may need to listen to key events too. By abstracting, it does not matter whether the product was selected using a click, a key, or anything else. The controller would then listen for the abstract event generated by the view.