HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/buyercall/buyercall/assets/components/widgets/call_settings_numbers.js
/* jshint esversion: 6 */
var $ = require('jquery');
var Backbone = require('backbone');

// Templates
var numberSelectTemplate = require('./templates/call_settings_numbers.tpl');

var NUMBERS_URL = `//${appConfig.server_url}/api/outbound/phonenumbers`;

// Allow user to select originating number of the Buyercall call
// Defaults to the one defined in the TWILIO_CALLER_ID app setting
var NumberSelectView = Backbone.View.extend({
    events: {
        'change select': 'handleChange'
    },

    template: numberSelectTemplate,

    initialize: function (options) {
        this.data = [];
        this.settings = options.settings || new Backbone.Model();

        this.render();
        this.listenTo(this.settings, 'change:fromNumberId', () => {
            this.render();
        });

        $.get(NUMBERS_URL).done((json) => {
            this.data = json.data;
            this.render();
            this.updateSettings();
        });
    },

    refreshSelection: function () {
        var id = this.settings.get('fromNumberId', null);
        for (var i = 0; i < this.data.length; i++) {
            this.data[i].selected = (this.data[i].id == id);
        }
    },

    updateSettings: function () {
        var sel = this.$('select')[0],
            fromNumberId = parseInt(sel.value, 10),
            fromNumberType = this.$('select option').
                                  eq(sel.selectedIndex).
                                  attr('data-type');

        this.settings.set({
            'fromNumberId': fromNumberId,
            'fromNumberType': fromNumberType,
        });
    },

    render: function () {
        this.refreshSelection();
        this.$el.html(this.template({ data: this.data }));
        return this;
    },

    handleChange: function () {
        this.updateSettings();
    }
});

module.exports = NumberSelectView;