如何从Jquery插件返回值数组

时间:2018-06-04 15:21:02

标签: jquery jquery-plugins jquery-select2

我有一个基于select2的插件。此插件用于实现带标签的自动完成功能。我想要做的就是从插件中返回所选标签,并访问插件外部的数据以保存它。 我已经拥有关于' onSelectionChanged'的数据。选项。

插件代码:

(function ($) {
    var _plugin_count = 1;
    var _plugin_prefix = 'jobtitle2_';

    var JobTitleSelect2 = function (element, options, plugin_count) {
        var instance = this;

        // These are the default settings.
        instance.settings = {
            active: 'Y',
            defaultItems: null,
            width: null,
            onSelectionChanged: function (item) {
                var data = instance.control.select2('data'); // I wan't to return this data
                console.log('data', data);              
            },
            onOpen: null,
            showAddButton: false,
            addButtonText: "Add Job Title",
            addButtonCallback: function () {
                $('<div></div>').EditJobTitle({
                    onSave: instance.settings.onAdd
                })
            },
            onAdd: function (item) {
                console.log('on add event triggered');
                var data = instance.control.select2('data');
                data.push({ id: item.Code, text: item.Description, color: item.Color });
                instance.control.select2('data', data);
            }
        };

        instance.plugin_count = plugin_count;
        instance.prefix = _plugin_prefix + plugin_count + '_';
        instance.control = $(element);

        instance.initialize(options);
        instance.Build();
    }

    JobTitleSelect2.prototype = {
        constructor: JobTitleSelect2,

        Build: function () {
            var instance = this;

            instance.CreateSelect2();
            instance.CreateEvents();
        },

        CreateEvents: function () {
            var instance = this;

            //if (instance.settings.onSelectionChanged) {
            //    instance.control.on('change', instance.settings.onSelectionChanged);
            //}

            //if (instance.settings.onOpen) {
            //    instance.control.on('select2-open', instance.settings.onOpen);
            //}

        },

        CreateSelect2: function () {
            var instance = this;

            var defaultItems = [];
            if (instance.settings.defaultItems) {
                if ($.isArray(instance.settings.defaultItems)) {
                    defaultItems = instance.settings.defaultItems;
                } else {
                    defaultItems.push(instance.settings.defaultItems);
                }
            }

            var options = clone(instance.settings);

            options.ajax = { // instead of writing the function to execute the request we use Select2's convenient helper
                url: "/Common/User/GetJobTitles.ashx",
                dataType: 'json',
                quietMillis: 250,
                data: function (term, page) {
                    return {
                        term: term, // search term
                        active: instance.settings.active
                    };
                },
                results: function (data, page) { // parse the results into the format expected by Select2.                                
                    return {
                        results: $.merge($.merge([], defaultItems), $.map(data, function (item) {
                            var elem =  {
                                text: item.JobName,
                                id: item.JobCode,
                                color: item.JobColor
                            };
                            if (instance.control.select2('data').some(e => e.id === elem.id) ) {
                                return;
                            }

                            return elem;
                        }))
                    };
                }
            };

            options.initSelection = function (element, callback) {
                var id = $(element).val();

                if (id !== "") {
                    $.ajax("/Common/User/GetJobTitle.ashx?jobtitle_id=" + encodeURIComponent(encodeURIComponent(id)), {
                        dataType: "json"
                    }).done(function (data) {
                        var item = { text: data.JobName, id: data.JobCode };
                        callback(item);
                    });
                }
            };

            if (instance.settings.width) {
                options.width = instance.settings.width;
                //options.formatSelectionCssClass =  function (data, container) { return "myCssClass"; },
            }

            instance.control.Select2Plus(options);

        },

        initialize: function (options) {
            var instance = this;

            instance.settings = $.extend(true, {}, instance.settings, options);
        }
    };


    $.fn.JobTitleSelect2 = function (options, args) {
        var instance = this.data('JobTitleSelect2');
        if (options === undefined || typeof options === 'object') {
            return this.each(function () {
                if (!instance) {
                    $.data(this, "JobTitleSelect2", new JobTitleSelect2(this, options, _plugin_count++));
                }
            });
        }
        return this;
    };

}(jQuery));

我调用插件的方式?

  $('#ddlJobTitle').JobTitleSelect2({
                showAddButton: true
           }); 

1 个答案:

答案 0 :(得分:0)

我没有返回值,而是在每次更改后访问所选数据,如下所示:

 // The way I called the plugin
  var JobTitles = $('#ddlJobTitle');
        $(JobTitles).JobTitleSelect2({
            showAddButton: true
        });

// The way I called After each change event:

    $(JobTitles).change(function() {
                var selections = ( JSON.stringify($(JobTitles).select2('data')) );
                console.log('Selected options: ' , selections);           
     });

参考文献:http://jsfiddle.net/Shady_Alset/e5tg5kLr/

修改 另一种解决方案是在单击保存按钮时获取所选数据:

var JobTitles = $('#ddlJobTitle');
var selections = $(JobTitles).select2('data') ;