Catch DOM events in custom .js controller

Hi,

I have a custom template(.hbs) with a button inside:

<button data-action="add_item" class="btn btn-primary btn-sm" aria-label="{{str "Add item"}}" role="link" type="button">
    <span class="action-label"> {{str "Add item"}}</span>
</button>

I´m trying to catch the button's click event in the controller like this:

({
    extendsFrom: 'RecordView',
    items: new Array(),

    initialize: function (options) {
        this._super('initialize', [options]);
        console.log('test');
        // app.view.View.prototype.initialize.call(this, options);
        this.context.on('button:add_item:click', this.addItem, this);
    },

    events: {
        //On click of our "button" element
        'click [data-action=add_item]': 'addItem',
    },

    addItem: function(){
        alert();
        myData=new Object();
        myData.field1 ='hola';
        myData.field2 ='mundo';

        this.items.push(myData);
        this.render();
    }
})

But doesn't work.

Thanks for your help.

Parents
  • So I see a couple of issues.

    this.context.on() does not work because you aren't generating any Backbone Events for this button.  Since you are just generating this button using a custom Handlebars template then you aren't wiring in Backbone events at all.

    http://backbonejs.org/#Events

    The events hash DOES allow you to subscribe to DOM events. But since you are extending the Record View then the way you are subscribing your click event overwrites all the existing events in the parent view.  This is probably not what you want.

    http://stackoverflow.com/questions/9403675/backbone-view-inherit-and-extend-events-from-parent

    For example, this works for me using just a regular Sidecar view.

    ({
        extendsFrom: '...',
        myEvents: {
            //On click of our "button" element
            'click [data-action=add_item]': 'addItem',
        },
        initialize: function (options) {
            this._super('initialize', [options]);
            if (this.events) {
                // Extend events hash with my events if one already exists
                _.extend(this.events, this.myEvents)
            } else {
                // Otherwise, just use my events
                this.events = this.myEvents;
            }
        },
        addItem: function(){
            alert();
        }
    
    })
    

    App Ecosystem @ SugarCRM

  • Thank you for reply, works perfectly, for another event, like onkeyup or onchange input, its the same method?

Reply Children