如何在Select2 4中使用Breeze?

时间:2015-05-21 14:50:39

标签: breeze jquery-select2 jquery-select2-4

如何使用Breeze在Select2 jQuery plugin中加载远程数据? built in ajax functionality uses jQuery但文档specifies that you can use the ajax property to setup your own remote data sources。使用ajax属性的breeze的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

我想出了一个很好的解决方案。此示例将针对Breeze的Todo示例中的Todo Server(例如Todo-Angular Sample)。

我的解决方案利用数据功能创建查询,连接Breeze&then故障功能以选择2的成功和失败功能,并使用Breeze' {{3}进行完整的分页功能}。

//Setting for the number of items to get per request
var numberPerPage = 10;

jQuery('select').select2({
    //Custom ajax method that uses breeze to get the results
    ajax: {
        transport: function (params, success, failure) {
            manager.executeQuery(params.data).then(function (data) {
                success(data.results);
            }).fail(function (data) {
                failure();
            });
            return { abort: function () { } };//Return a dummy abort function since select2 requires one but Breeze doesn't have that functionality
        },
        data: function (params) {
            var query = {
                from: 'Todos',
                orderBy: ['Description'],
                where: {
                    or: [
                        { 'Description': { 'Contains': params.term } },
                    ]
                },
                take: numberPerPage,
                skip: (numberPerPage * ((params.page || 1) - 1))
            };
            return new breeze.EntityQuery(query);//Return a Breeze query as the data, which we'll request in the transport
        },
        processResults: function (data, params) {
            return {
                //Convert the returned objects into select2 friendly objects
                results: jQuery.map(data, function (val) {
                    return {
                        id: this.Id,
                        text: this.Description
                    };
                }),
                pagination: {//Must return this to get paging to work
                    more: data.length == numberPerPage//If the data returned a total page, we should try again for more
                }
            };
        },
    }
});