Paul Thompson
Paul Thompson

Reputation: 77

Backbone.js View events disable enable

If I have a View in backbone.js and it has an event in the events list:

events: {
    'click #somebutton': 'clicked'         
},
clicked: function () {
    console.log('clicked');
}

How can I then disable/enable that event? So for instance if its clicked then the event is removed (the button remains on screen but is greyed out etc). When some other part of the view is updated or whatever the event enabled. Sure I can use jquery but I want to know if this functionality is available in backbone.

Thanks for any answers

Paul

Upvotes: 2

Views: 4749

Answers (2)

jmk2142
jmk2142

Reputation: 8581

You can always use delegateEvents() and undelegateEvents() to redo your event binding between the DOM and your Backbone View. That said, I usually just keep the event handler and add a conditional in the handler.

// .disabled class (CSS) grays out the button

clicked: function(event) {
    var buttonEl = $(event.currentTarget);

    if (buttonEl.hasClass('disabled')) {
        // Do nothing
    } else {
        // Do something AND...
        buttonEl.addClass('disabled');
    }
}

Then you can have your other view or code simply removeClass('disabled') when you want to restore functionality.

UPDATE - disabled property

See comments, but a simpler, much better solution is to use the disabled property disabled="disabled" of buttons.

Upvotes: 2

Anshu
Anshu

Reputation: 7853

Use delegateEvents and undelegateEvents for binding and unbinding events. Check for reference: delegateEvents

Upvotes: 2

Related Questions