更新YUI DataTable时避免页面闪烁

时间:2010-09-07 09:10:52

标签: javascript asp.net firefox yui yui-datatable

我正在使用jlinq库来扩展linq到json,因此我过滤了我的json数据。考虑我有一个json数据,在页面加载时绘制一个yui数据表,有100行。我正在做一个客户端过滤器,它将减少我的json数据,我现在正在重绘相同的数据表。它会发生什么效果很好,但会产生恼人的闪烁效果......

我从过滤器文本框的 onkeyup 事件中调用以下方法,

function showusersfilter(txt) {
    var jsondata = document.getElementById("ctl00_ContentPlaceHolder1_HfJsonString").value;
    jsondata = jQuery.parseJSON(jsondata);
    var results = jLinq.from(jsondata.Table)
                 .startsWith("name", txt)
                 .select();
    var jsfilter = { "Table": results };

    var myColumnDefs = [
         { key: "userid", label: "UserId", hidden: true },
         { key: "name", label: "Name", sortable: true, sortOptions: { defaultDir: YAHOO.widget.DataTable.CLASS_DESC} },
         { key: "designation", label: "Designation" },
         { key: "phone", label: "Phone" },
         { key: "email", label: "Email" },
         { key: "role", label: "Role", sortable: true, sortOptions: { defaultDir: YAHOO.widget.DataTable.CLASS_DESC} },
         { key: "empId", label: "EmpId" },
         { key: "reportingto", label: "Reporting To", sortable: true, sortOptions: { defaultDir: YAHOO.widget.DataTable.CLASS_DESC} },
         { key: "checkbox", label: "", formatter: "checkbox", width: 20 }
     ];
    var jsonObj = jsfilter;
    var target = "datatable";
    var hfId = "ctl00_ContentPlaceHolder1_HfId";
    generateDatatable(target, jsonObj, myColumnDefs, hfId);
}

我的文本框看起来

<asp:TextBox ID="TxtUserName" runat="server" CssClass="text_box_height_14_width_150" onkeyup="showusersfilter(this.value);"></asp:TextBox>

和我的generateatatable函数,

function generateDatatable(target, jsonObj, myColumnDefs, hfId) {
    var root;
    for (key in jsonObj) {
        root = key; break;
    }
    var rootId = "id";
    if (jsonObj[root].length > 0) {
        for (key in jsonObj[root][0]) {
            rootId = key; break;
        }
    }
    YAHOO.example.DynamicData = function() {
        var myPaginator = new YAHOO.widget.Paginator({
            rowsPerPage: 25,
            template: YAHOO.widget.Paginator.TEMPLATE_ROWS_PER_PAGE,
            rowsPerPageOptions: [10, 25, 50, 100],
            pageLinks: 10
        });

        // DataSource instance 
        var myDataSource = new YAHOO.util.DataSource(jsonObj);
        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
        myDataSource.responseSchema = { resultsList: root, fields: new Array() };
        myDataSource.responseSchema.fields[0] = rootId;
        for (var i = 0; i < myColumnDefs.length; i++) {
            myDataSource.responseSchema.fields[i + 1] = myColumnDefs[i].key;
        }
        // DataTable configuration 
        var myConfigs = {
            sortedBy: { key: myDataSource.responseSchema.fields[1], dir: YAHOO.widget.DataTable.CLASS_ASC }, // Sets UI initial sort arrow
            paginator: myPaginator
        };
        // DataTable instance 
        var myDataTable = new YAHOO.widget.DataTable(target, myColumnDefs, myDataSource, myConfigs);
        myDataTable.resizeHack = function()
        { this.getTbodyEl().parentNode.style.width = "100%"; }
        myDataTable.subscribe("rowMouseoverEvent", myDataTable.onEventHighlightRow);
        myDataTable.subscribe("rowMouseoutEvent", myDataTable.onEventUnhighlightRow);
        myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow);
        myDataTable.subscribe("checkboxClickEvent", function(oArgs) {
            var hidObj = document.getElementById(hfId);
            var elCheckbox = oArgs.target;
            var oRecord = this.getRecord(elCheckbox);
            var id = oRecord.getData(rootId);
            if (elCheckbox.checked) {
                if (hidObj.value == "") {
                    hidObj.value = id;
                }
                else {
                    hidObj.value += "," + id;
                }
            }
            else {
                hidObj.value = removeIdFromArray("" + hfId, id);
            }
        });
        myPaginator.subscribe("changeRequest", function() {

            if (document.getElementById(hfId).value != "") {
                if (document.getElementById("ConfirmationPanel").style.display == 'block') {
                    document.getElementById("ConfirmationPanel").style.display = 'none';
                }
                document.getElementById(hfId).value = "";
            }
            return true;
        });
        myDataTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
            oPayload.totalRecords = oResponse.meta.totalRecords;
            return oPayload;
        }
        return {
            ds: myDataSource,
            dt: myDataTable
        };
    } ();
}

修改

我甚至在keyup事件上使用延迟仍然会发生闪烁,

var timer;
    function chk_me(){
       clearTimeout(timer);
       timer = setTimeout(function validate(){ showusersfilter(document.getElementById("ctl00_ContentPlaceHolder1_TxtUserName").value);}, 1000);
    }

2 个答案:

答案 0 :(得分:1)

为什么每次过滤数据时都会创建一个新的dataTable?您不需要此任务。 只需使用其dataSource的sendRequest方法将过滤后的数据提供给其dataTable

我创建了这个jsonObject来模拟过滤后的数据

var jsonObject = {
    "root":[
        {id:"5", userid:"1", name:"ar", designation:"1programmer", phone:"15484-8547", email:"1arthurseveral@yahoo.com.br", role:"1developer", empId:"1789", reportingto:"116"},
        {id:"5", userid:"2", name:"br", designation:"2programmer", phone:"25484-8547", email:"2arthurseveral@yahoo.com.br", role:"2developer", empId:"2789", reportingto:"216"},
        {id:"5", userid:"3", name:"cr", designation:"3programmer", phone:"35484-8547", email:"3arthurseveral@yahoo.com.br", role:"3developer", empId:"3789", reportingto:"316"},
        {id:"5", userid:"4", name:"dr", designation:"4programmer", phone:"45484-8547", email:"4arthurseveral@yahoo.com.br", role:"4developer", empId:"4789", reportingto:"416"},
        {id:"5", userid:"5", name:"er", designation:"5programmer", phone:"55484-8547", email:"5arthurseveral@yahoo.com.br", role:"5developer", empId:"5789", reportingto:"516"}
    ],
    "another":[
        {id:"5", userid:"5", name:"er", designation:"5programmer", phone:"55484-8547", email:"5arthurseveral@yahoo.com.br", role:"5developer", empId:"5789", reportingto:"516"},
        {id:"5", userid:"4", name:"dr", designation:"4programmer", phone:"45484-8547", email:"4arthurseveral@yahoo.com.br", role:"4developer", empId:"4789", reportingto:"416"},
        {id:"5", userid:"3", name:"cr", designation:"3programmer", phone:"35484-8547", email:"3arthurseveral@yahoo.com.br", role:"3developer", empId:"3789", reportingto:"316"},
        {id:"5", userid:"2", name:"br", designation:"2programmer", phone:"25484-8547", email:"2arthurseveral@yahoo.com.br", role:"2developer", empId:"2789", reportingto:"216"},
        {id:"5", userid:"1", name:"ar", designation:"1programmer", phone:"15484-8547", email:"1arthurseveral@yahoo.com.br", role:"1developer", empId:"1789", reportingto:"116"}
    ]
};

初始化时

(function() {
    var Yutil      = YAHOO.util,
        Ywidget    = YAHOO.widget

        DataTable  = Ywidget.DataTable,
        Paginator  = Ywidget.Paginator,
        DataSource = Yutil.DataSource;

    YAHOO.namespace("_3657287"); // QUESTION ID - SEE URL

    var _3657287 = YAHOO._3657287;

    /**
      * paginator
      */
    var paginator = new Paginator({
        rowsPerPage:25,
        template:Paginator.TEMPLATE_ROWS_PER_PAGE,
        rowsPerPageOptions:[10, 25, 50, 100],
        pageLinks:10
    });

    /**
      * dataSource
      *
      * As you have static data, I pass an empty "jsonObject" to its constructor
      */
    var dataSource = new DataSource({root:[]});
    dataSource.responseType = DataSource.TYPE_JSON;
    dataSource.responseSchema = {resultsList:"root", fields:[]};

    var columnSettings = [
        {key:"userid", label:"UserId"},
        {key:"name", label:"Name"},
        {key:"designation", label:"Designation"},
        {key:"phone", label:"Phone"},
        {key:"email", label:"Email"},
        {key:"role", label:"Role"},
        {key:"empId", label:"EmpId"},
        {key:"reportingto", label:"Reporting To"}
    ];

    dataSource.responseSchema.fields[0] = "id";
    for (var i = 0; i < columnSettings.length; i++) {
        dataSource.responseSchema.fields[i + 1] = columnSettings[i].key;
    }

    /**
      * Notice initialLoad equal To false (I suppose your dataTable IS NOT pre-populated)
      */
    var dataTableSettings = {
        paginator:paginator,
        initialLoad:false
    };

    /**
      * dataTable
      *
      * Notice IT IS STORED in the namespace YAHOO._3657287
      */
    _3657287.dataTable = new DataTable("container", columnSettings, dataSource, dataTableSettings);
})();

现在,当您想要过滤数据时,请执行以下操作(注意sendRequest方法)

var i = 0;
YAHOO.util.Event.addListener("reload", "keyup", function(e) {
    YAHOO._3657287.dataTable.getDataSource().sendRequest(null, {
        success:function(request, response, payload) {

            /**
              * initializeTable method clear any data stored by The datatable
              */
            this.initializeTable();

            if(i === 0) {
                this.getRecordSet().setRecords(jsonObject["root"], 0);

                i++;
            } else {
                this.getRecordSet().setRecords(jsonObject["another"], 0);

                i--;
            }

            this.render();
        },
        scope:YAHOO._3657287.dataTable,
        argument:null
    });
});

您可以看到here工作正常

但如果效果再次出现(注意我只是使用相关部分 - 也不是特殊功能也不是别的东西)可能会发生,因为

  • keyup活动
  • dataTable呈现

您可以按如下方式设置变量

var isProcessing = false;

YAHOO.util.Event.addListener("reload", "keyup", function(e) {
    if(isProcessing) {
        return;
    }

    isProcessing = true;

    YAHOO._3657287.dataTable.getDataSource().sendRequest(null, {
        success:function(request, response, payload) {
             // as shown above

             isProcessing = false;
        }
    });
}

另请参阅herehere

答案 1 :(得分:0)

问题可能与该行有关:

myDataTable.resizeHack = function()
        { this.getTbodyEl().parentNode.style.width = "100%"; }

由于您要调整表格的宽度,因此可以合理地假设需要在屏幕上重新绘制表格,从而导致闪烁。