2
votes

Hopefully I'm missing something simple... I'm trying to do something basic in that I want a view's attribute hash to update automatically when the model changes.

If you look at the attributes: section, you can see how i'm trying to dynamically set them. However, they don't seem to be updating with the underlying model changes.

Any ideas? Thank you!

NS.CP.ColorView = Backbone.View.extend({
    initialize: function(){
        _.bindAll(this);
        this.model.bind('change', this.render);
    },
    attributes: function(){
        return {
            'class': (this.model.get('active') == 'true') ? 'active' : '',
            'data-code': this.model.get('modifier'),
            'data-hex': this.model.get('color'),
            'data-image': this.model.get('image'),
            'data-match': this.model.get('matchBody'),
            'style': 'background-color: ' + this.model.get('color')
        };
    },
    events: {
        'click': 'renderFrame',
        'activate': 'activate',
        'deactivate': 'deactivate'
    },
    tagName: 'li',
    render: function(){

        console.log(this);

        var $el = this.$el;

        if( this.model.get('active') == 'true' && $el.closest('.model_colorpicker').hasClass('body-colors') ){

            // Change border color on click
            $('.color-frame').css( 'border-color', $el.data('hex') );
        }

        return this.el;
    },
    activate: function(){
        this.model.set('active', 'true');
    },
    deactivate: function(){
        this.model.set('active', 'false');
    },
    renderFrame: function(){
        if( !this.$el.hasClass('active') ){ this.$el.trigger('activate').siblings().trigger('deactivate'); }
        else { this.$el.trigger('deactivate'); }
    }
});
1

1 Answers

7
votes

The only time the attributes hash is calculated is when the view is created, you will need to do some work yourself to update it, here is one way,

initialize : function(){
  this.listenTo(this.model, 'change', this.modelChange);
},
modelChange : function(){
  this.$el.attr(_.extend({}, _.result(this, 'attributes')));
}