Setting id and className dynamically in Backbone.js views

后端 未结 8 1879
生来不讨喜
生来不讨喜 2021-01-29 19:24

I am in process of learning and using Backbone.js.

I have an Item model and a corresponding Item view. Each model instance has item_class and item_id attributes, that I

8条回答
  •  情深已故
    2021-01-29 20:11

    Here's a minimal way to change the class of the view's element dynamically via a model and update it on model changes.

    var VMenuTabItem = Backbone.View.extend({
        tagName: 'li',
        events: {
            'click': 'onClick'
        },
        initialize: function(options) {
    
            // auto render on change of the class. 
            // Useful if parent view changes this model (e.g. via a collection)
            this.listenTo(this.model, 'change:active', this.render);
    
        },
        render: function() {
    
            // toggle a class only if the attribute is set.
            this.$el.toggleClass('active', Boolean(this.model.get('active')));
            this.$el.toggleClass('empty', Boolean(this.model.get('empty')));
    
            return this;
        },
        onClicked: function(e) {
            if (!this.model.get('empty')) {
    
                // optional: notify our parents of the click
                this.model.trigger('tab:click', this.model);
    
                // then update the model, which triggers a render.
                this.model.set({ active: true });
            }
        }
    });
    

提交回复
热议问题