Issues (105)

js/app/views/default-variant-collection-view.js (1 issue)

1 View Code Duplication
define(function(require) {
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
2
    'use strict';
3
4
    var DefaultVariantCollectionView;
5
    var BaseView = require('oroui/js/app/views/base/view');
6
    var mediator = require('oroui/js/mediator');
7
    var $ = require('jquery');
8
    var _ = require('underscore');
9
10
    DefaultVariantCollectionView = BaseView.extend({
11
        $collection: null,
12
13
        options: {
14
            defaultSelector: '[name$="[default]"]',
15
            itemSelector: '[data-role="content-variant-item"]',
16
            defaultItemClass: 'content-variant-item-default'
17
        },
18
19
        /**
20
         * @inheritDoc
21
         */
22
        constructor: function DefaultVariantCollectionView() {
23
            DefaultVariantCollectionView.__super__.constructor.apply(this, arguments);
24
        },
25
26
        /**
27
         * @inheritDoc
28
         */
29
        initialize: function(options) {
30
            this.options = $.extend(true, {}, this.options, options || {});
31
32
            this.$el.on(
33
                'click',
34
                this.options.defaultSelector,
35
                _.bind(
36
                    function(e) {
37
                        this.onDefaultChange($(e.target));
38
                    },
39
                    this
40
                )
41
            );
42
            mediator.on('cms:content-variant-collection:add', this.handleAdd, this);
43
            mediator.on('cms:content-variant-collection:remove', this.handleRemove, this);
44
45
            this.handleAdd();
46
        },
47
48
        handleRemove: function($container) {
49
            // Check is default variant removed
50
            if ($container.find(this.options.defaultSelector + ':checked').length === 0) {
51
                this.checkDefaultVariant();
52
            }
53
        },
54
55
        handleAdd: function() {
56
            if (this.$el.find(this.options.itemSelector).length &&
57
                this.$el.find(this.options.defaultSelector + ':checked').length === 0
58
            ) {
59
                this.checkDefaultVariant();
60
            }
61
        },
62
63
        checkDefaultVariant: function() {
64
            var $default = this.$el.find(this.options.defaultSelector + ':not(:checked)').first();
65
            $default.prop('checked', true).trigger('change');
66
67
            this.onDefaultChange($default);
68
        },
69
70
        onDefaultChange: function($default) {
71
            this.$el.find('.' + this.options.defaultItemClass).removeClass(this.options.defaultItemClass);
72
            $default.closest(this.options.itemSelector).addClass(this.options.defaultItemClass);
73
        }
74
    });
75
76
    return DefaultVariantCollectionView;
77
});
78