Skip to content

Socket.IO Integration

ivaynberg edited this page Jul 6, 2012 · 2 revisions

Below is a small example of how Socket.IO can be used as a transport for Select2

    $(".tagSelect").select2({
        initSelection: function() {
            return  [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}];
        },
        multiple: true,
        placeholder: 'Add tags here',
        query: function(query) {
            var bound = false;
            //to initialize the socket listener only once
            if (!bound) {
                Backbone.socket.on("Tag:autocomplete", function(response) {
                    var data = {
                        results: []
                    };
                    //Push the query term first, so it ll become selectable (kinda like adding new tag)
                    data.results.push({
                        id: query.term,
                        text: query.term
                    })
                    _.each(JSON.parse(response.result), function(tag) {
                        data.results.push({
                            id: tag.name,
                            text: tag.name
                        });
                    })
                    query.callback(data)
                });
                bound = true;
            }

            if (query.term != '') {
                Backbone.socket.emit("Tag:autocomplete", {
                    term: query.term
                });
            }
        }
    });
Clone this wiki locally