显示/隐藏div - DRY

时间:2015-08-24 09:12:07

标签: javascript backbone.js

我有3个观看次数,SectionAViewSectionBViewSectionCView。 每个视图都有2个单选按钮,YesNo

当我在Yes中选择SectionAView时,它应显示SectionBView。选择“否”应显示SectionCView(并隐藏SectionBView

应用程序可以有很多视图,所以我想我的问题是让事情变得更干一些,并且可能是解决这个问题的最佳方法吗?

我有这样的事情:

var Section = Backbone.Model.extend({
    defaults: {
        block: null
    }
});

var List = Backbone.Collection.extend({
    model: Section
});

var SectionAView = Backbone.View.extend({
    el: 'body',

    initialize: function() {
        this.model = new Section();
        this.collection = new List();
        this.listenTo(this.model, "change", this.render);
        this.render();
    },
    events: {
         'click .section-a': 'updateElement'
    },
    render: function(e) {
         this.$el.find('.section-b').hide();
         return this;
    },
    updateElement: function(e) {
        var $target = $(e.target);
        var activeValue = $target.val();
        // Default - SectionA is displayed (at all times)
       this.model.set('block', 'section-a');
       this.collection.push(this.model);
       if (activeValue == 'no') {
           this.$el.find('.section-b').show();
           this.$el.find('.section-c').hide();
       } else {
           this.$el.find('.section-c').show();
           this.$el.find('.section-b').hide();
       }
     }
   });

   var SectionBView = Backbone.View.extend({
        el: 'body',
        model: Section,

        initialize: function() {
             this.render();
        },
        render: function(e) {
            this.$el.find('.section-b').hide();
            return this;
        },
      });

      var SectionCView = Backbone.View.extend({
            el: 'body',
            initialize: function() {
                this.render();
            },
            render: function(e) {
                this.$el.find('.section-c').hide();
                return this;
            }

        });

HTML:

    <div class="section-a" data-active-value="true">
        <h2>Section A</h2>
        <label>Yes<input type="radio" name="section-a" class="section-a" value="yes" /></label>
        <label>No<input type="radio" name="section-a" class="section-a" value="no" /></label>
    </div>

    <div class="section-b" data-active-value="">
        <h2>Section B</h2>
        <label>Yes<input type="radio" name="section-b" class="section-b" value="yes" /></label>
        <label>No<input type="radio" name="section-b" class="section-b" value="no" /></label>
    </div>

    <div class="section-c">
        <h2>Section C</h2>
        <label>Yes<input type="radio" name="section-c" class="section" value="yes" /></label>
        <label>No<input type="radio" name="section-c" class="section" value="no" /></label>
    </div>

0 个答案:

没有答案