Search code examples
javascriptbackbone.js

How to use variables in Backbone events object?


Currently my code looks like this:

events: {
    'click .update-url': 'update_url',
    'click .show-password': 'show_password'
},

but for touch devices I want to use touchstart instead of click as the event hence I want to use variables like this:

var click_event = is_touch_device ? 'touchstart' : 'click';

...

events: {
    click_event + ' .update-url': 'update_url',
    click_event + ' .show-password': 'show_password'
},

But it doesn't work. How to use variables in this way while still using the event's object in Backbone?


Solution

  • In case anyone has the same issue, I fixed it this way:

        events: function() {
            var _events = {};
            _events[click_event + ' a.menu-toggle'] = 'toggle_menu';
            _events[click_event + ' a.close-menu, a.authenticate'] = 'close_menu';
            _events[click_event + ' ul.menu-links > li.dd'] = 'toggle_sub_menu';
            _events[click_event + ' #search-form-lg button'] = 'expand_search';
            return _events;
        },