ogregor
@ogregor
арендатор vpn сервера debian

Как правильно сделать обновление параметров уже инициализированного плагина?

Здравствуйте, каким образом можно произвести обновление уже проинициализированного плагина, вопрос встал ребром на перерегистрации коллбек функций.

$('.get-city').geoSelector()

  $('.get-city').geoSelector('set',
                    {minInputChar: 3,
                        regionID: 20,
                        events: {
                            onGSData: function (e, el, resp) {
                                console.log('onGSDAta обновленная функция: ' + resp);
                            }
                        }
                    });


Это мой первый планин, так что многие вещи подсмотрены но не осознанны.
Вот так просиходит регистрация колбек функций из настроек до инициализации:

$.each(widget.config.events, function (key, value) {
            if (typeof value === 'function') {
                widget.element.on(key + '.gs', function (e, param) {
                    // key имя передаваемой функции.
                    // передаем значение через замыкание
                    return value(e, widget.element, param);
                });
            }
  });


Сам плагин:
;(function ($) {
    var defaults = {
        regionID: undefined,
        minInputChar: 1,
        bindEvent: 'keyup',
        events: {
            onGsData: function (data) {},
            onGsError: function (text) {},
            onGsCityStart: function () {},
            onGsCityData: function (data) {}
        }
    };
    function GeoSelector(element, options) {
        var widget = this;
        widget.config = $.extend({}, defaults, options);
        widget.element = element;
        
         //  widget.updateCallBacks();
              
          $.each(widget.config.events, function (key, value) {
            if (typeof value === 'function') {
                widget.element.on(key + '.gs', function (e, param) {
                    // key имя передаваемой функции.
                    // передаем значение через замыкание
                    return value(e, widget.element, param);
                });
            }
        });
     
        widget.init();
        if (widget.config.regionID !== undefined) {
            widget.getData('http://admin.evildevel.com/api/geo/city.json', 'cities', 'region=' + widget.config.regionID);
        }
        
        widget.inputContainer.on(widget.config.bindEvent, function (e) {
        widget.config = $.extend({}, widget.config, defaults);  
                             
       //     widget.updateCallBacks();
            
            widget.regionContainer.empty();
            var str = widget.inputContainer.val();
            if (str.length >= widget.config.minInputChar) {
                setTimeout(function () {
                    widget.getData('http://admin.evildevel.com/api/geo/region.json', 'regions', 'name=%' + str + '%');
                }, 600);
            }
        });
    }
    ;
    GeoSelector.prototype = {
        init: function () {
            this.element.addClass('gs-container');
            var selectContainer = $('<div/>').addClass('gs-select-container').appendTo(this.element);
            this.inputContainer = $('<input/>').addClass('gs-input-container').appendTo(selectContainer);
            this.regionContainer = $('<div/>').addClass('gs-region-container').appendTo(selectContainer);
            this.cityContainer = $('<div>').addClass('gs-city-container').appendTo(this.element);
        },
        getData: function (url, output, input) {
            var _this = this;
            $.ajax({
                type: 'GET',
                url: url,
                data: input,
                crossDomain: true,
                contentType: 'application/json; charset=utf-8',
                dataType: 'json'
            }).done(function (data) {

                var string = JSON.stringify(data);
                _this.regionContainer.empty();
                _this.cityContainer.empty();

                if (output === 'regions') {
                    _this.constructRegBlock(data);
                    _this.element.trigger('onGsData.gs', string);

                    $('.gs-region-item').on('click', function () {
                        _this.element.trigger('onGsCityStart.gs');
                        _this.getData('http://admin.evildevel.com/api/geo/city.json', 'cities', 'region=' + $(this).attr('data-item'));
                        _this.inputContainer.val($(this).text());
                    });
                }
                if (output === 'cities') {
                    _this.constructCityBlock(data);
                    _this.element.trigger('onGsCityData.gs', string);
                }
                $(data).empty();            
            }).fail(function (data) {
                _this.element.triggerHandler('onGsError.gs', data);
            });
        },
        constructRegBlock: function (regions) {
            var x, y;
            for (x = 0, y = regions.length; x < y; x++) {
                $('<div/>', {
                    text: regions[x][1],
                    class: 'gs-region-item'
                }).attr('data-item', regions[x][0]).appendTo(this.regionContainer);
            }
        },
        constructCityBlock: function (cities) {
            var x, y;
            this.cityContainer.empty();
            for (x = 0, y = cities.length; x < y; x++) {
                $('<div/>', {
                    text: cities[x][1],
                    class: 'gs-city-item'
                }).attr('data-item', cities[x][0]).appendTo(this.cityContainer);
            }
        },
        
        updateCallBacks: function() {
           var  _this = this;
             $.each(_this.config.events, function (key, value) {
                 console.log(key +'-'+value);
            if (typeof value === 'function') {
                _this.element.on(key + '.gs', function (e, param) {
                    // key имя передаваемой функции.
                    // передаем значение через замыкание
                    console.log(value,_this.element,param);
                    return value(e, _this.element, param);
                });
            }
        });
        }
    };
    $.fn.geoSelector = function (options) {

        if (arguments[0] === 'set') {
            defaults = $.extend({}, defaults, arguments[1]);
        } 
        else if (arguments[0] === 'get') {
         
        } 
        else {
            if (typeof options !== 'object' && options !== undefined) {
                var params = {};
                $(arguments).each(function (index, value) {
                    // получим имя n члена объекта defaults
                    var str = Object.keys(defaults)[index];
                    params[str] = value;
                    options = params;
                });
            }
            new GeoSelector(this.first(), options);
            return this.first();
        }
    };
})(jQuery);


После изменения настроек новая колбек функция успешно записывается в настройки плагина, но вот вызова этой новой функции не происходит. Что можно в этом случае сделать?
  • Вопрос задан
  • 92 просмотра
Решения вопроса 1
ogregor
@ogregor Автор вопроса
арендатор vpn сервера debian
onGSData !== onGsData из за опечатки не работало.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
summer Ярославль
от 100 000 до 140 000 ₽
КРАФТТЕК Санкт-Петербург
от 60 000 до 80 000 ₽
19 апр. 2024, в 20:43
20000 руб./за проект
19 апр. 2024, в 20:11
500 руб./за проект