0
votes

I'd like to call a method in my view when its attributes property is updated. The following code gives me an error: undefined is not a function.

SimpleView = Backbone.View.extend({

    initialize: function(){
        this.attributes = _.extend(this.attributes, Backbone.Events); // update
        this.attributes.on('change', this.updateAttributes(), this);
    }

});

How can I elegantly bind an event listener to the attributes?

JSFiddle here

UPDATE: I figured I have to extend attributes with Backbone.Events so I can listen to changes. Yeah... So now I don't get anymore errors, but still nothing happens. Any help would be largely appreciated.

1
Are you sure you want to listen to the attributes of the view or is the model what you refer to? - Puigcerber
Absolutely certain. I'm referring to the attributes that will be added to the html tag of this view (in my case 'data-type'). - Westerfaq
So for example, you can re-render the view every time the attributes of the model change this.listenTo(this.model, 'change', this.render, this); - Puigcerber
That would be great, but the view attributes are set independently from the model attributes. I was under the impression the on() method worked on any object. Do you know why it doesn't work in this case? - Westerfaq
No problem, I just added a JSFiddle to my question. - Westerfaq

1 Answers

0
votes

Although I would recommend you to use a model for holding the attributes, if you want to stay with your current approach, you need to manually trigger the event.

this.attributes.trigger('change');

I have updated your JSFiddle so you can get an idea of how it works.