Ag-grid视口:无法读取未定义的属性“ bind” [英] Ag-grid viewport: cannot read property 'bind' of undefined

查看:146
本文介绍了Ag-grid视口:无法读取未定义的属性“ bind”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在复制ag-grid Viewport示例,将其放置在代表表的对象中,而不是匿名函数中。考虑到完全相同的代码,我不明白为什么它会在尝试连接到模拟服务器时给我标题中的错误。



这里是该代码似乎不起作用:

 函数ViewportDatasource(mockServer){
this.mockServer =模拟服务器;
this.connectionId = this.mockServer.connect(this.eventListener.bind(this));
}

ViewportDatasource.prototype.eventListener = function(event){
switch(event.eventType){
case'rowCountChanged':
this。 onRowCountChanged(event);
休息时间;
案例 rowData:
this.onRowData(event);
休息时间;
案例 dataUpdated:
this.onDataUpdated(event);
休息时间;
}
};

这里是整个对象:

  function WatcherTable($ rootScope,$ scope,$ http){

this.FIELD_KEY_ID = id;
this.FIELD_KEY_ISSUER_SHORT_DESC = isd;
this.FIELD_KEY_ISSUER = iss;
this.FIELD_KEY_CUSIP = cus;
this.FIELD_KEY_ISIN = isin;
this.FIELD_KEY_BOARD_LABEL = lbl;
this.FIELD_KEY_IND_SECT_LABEL = isl;
this.FIELD_KEY_CURR = cur

this.FIELD_KEY_BEST_BID_SIZE = bBidSz;
this.FIELD_KEY_BEST_BID_PRICE = bBidPrc;
this.FIELD_KEY_BEST_ASK_PRICE = bAskPrc;
this.FIELD_KEY_BEST_ASK_SIZE = bAskSz;
this.FIELD_KEY_BEST_BID_SPREAD = bBidSpd;
this.FIELD_KEY_BEST_ASK_SPREAD = bAskSpd;

this.FIELD_KEY_ORDER_BID_SIZE = oBidSz;
this.FIELD_KEY_ORDER_BID_PRICE = oBidPrc;
this.FIELD_KEY_ORDER_ASK_PRICE = oAskPrc;
this.FIELD_KEY_ORDER_ASK_SIZE = oAskSz;
this.FIELD_KEY_ORDER_BID_SPREAD = oBidSpd;
this.FIELD_KEY_ORDER_ASK_SPREAD = oAskSpd;

this.headerMyOrder = ORDER;
this.headerMyBidOrder = BID ORDER;
this.headerMyAskOrder = ASK ORDER;


this.cols = [{
headerName:安全信息,
marryChildren:true,
子级:[{
headerName :发行人简短说明,
字段:this.FIELD_KEY_ISSUER_SHORT_DESC,

//宽度:0,
//隐藏:true
},
{
headerName:行业标签,
字段:this.FIELD_KEY_IND_SECT_LABEL,
//宽度:80,
过滤器: set,
filterParams: {值:[广告,航空航天/国防,农业,航空公司,服装,汽车制造商,汽车零部件,银行,基本材料,饮料 ,生物技术,建筑材料,化学药品,煤炭,商业服务,通讯,计算机,循环消费品,非循环消费品,化妆品/个人护理 ,分销/批发,多元化,电气设备与设备,电子ics,能源,替代能源,工程与建筑,娱乐,机械建筑与采矿,家用产品/商品工业,保险,互联网,投资公司 ,铁/钢,袋鼠,休闲时间,住宿,机械建设与采矿,机械多样化,媒体,金属制造/硬件,采矿, '杂项制造商','跨国公司','办公室家具','办公室/业务','石油和天然气','石油和天然气服务','包装和容器','药品','管道','房地产,区域(州/省),房地产投资信托基金,零售,储蓄和贷款],
newRowsAction:'keep'},
},
{
headerName:板标签,
字段:this.FIELD_KEY_BOARD_LABEL,
//宽度:80,
过滤器:文本,
filterParams:{适用于: true}

},{
headerName: CUSIP,
字段:this.FIELD_KEY_CUSIP,
//宽度:150,
// suppressFilter:true
},
{
headerName: ISIN,
栏位:this.FIELD_KEY_ISIN,
//宽度:150,
// suppressFilter:true
},
{
headerName: Currency,
栏位:this.FIELD_KEY_CURR,
//宽度:150,
// suppressFilter:true
}
]},
{
headerName:最佳,
marryChildren:true,

儿童:[{
headerName:出价大小,
固定:正确,
字段:this.FIELD_KEY_BEST_BID_SIZE,
cellStyle:{'border-left':'1px solid#E82043','color':'#E82043','font-weight':'bold','text-align ':'right'},
cellRenderer:BidRenderer,
过滤器:'number',


// width:125,
// suppressFilter:true
},{
headerName: Bid Price,
pinned:'right',
栏位:this.FIELD_KEY_BEST_BID_PRICE,
cellStyle:{'border-right':'1px solid#E82043','color':'#E82043','font-weight':'bold','text-align': 'right'},
// cellRenderer: animateShowChange,
cellFormatter:numberFormatter,
cellRenderer:BidRenderer,
width:125,
filter:'number' ,


// suppressFilter:true
},
{
headerName:问价,
固定为'right',
字段:this.FIELD_KEY_BEST_ASK_PRICE,
// cellRenderer:'animateShowChange',
cellFormatter:numberFormatter,
cellRenderer:AskRenderer,
cellStyle:{'color':' #19B092','font-weight':'bold','text -align':'right'},
过滤器:'number',
//宽度:125,
// suppressFilter:true
},
{
headerName:要求大小,
固定:'right',
字段:this.FIELD_KEY_BEST_ASK_SIZE,
cellStyle:{'border-right':'1px solid#19B092', 'color':'#19B092','font-weight':'bold','text-align':'right'},
cellRenderer:AskRenderer,
filter:'number',
// width:125,
// suppressFilter:true
}]
}];


// definizione della tabella ///// rowModelType:'virtual',rowModelType:'pagination',



这.table = {
showPrice:true,
showSpread:true,
orderSize:0,
orderFilter:'',
enableServerSideFilter:true,
enableServerSideSorting :true,
sortingOrder:['desc','asc',null],
enableColResize:true,
debug:true,
rowSelection:'multiple',
rowDeselection:true,
columnDefs:this.cols,
rowModelType:'viewport',
headerHeight:20,
rowHeight:20,
viewportRowModelPageSize:30,
viewportRowModelBufferSize:15,
inhibitorColumnVirtualization:true,
preventMenuColumnPanel:true,
onCellDoubleClicked:WatcherTable.protot ype.onCellDoubleClicked.bind(this,$ rootScope),
getContextMenuItems:WatcherTable.prototype.getContextMenuItems.bind(this,$ rootScope),
getMainMenuItems:WatcherTable.prototype.getMainMenuItems.bind(this,$ rootScope ),
getRowNodeId:function(data){
//代码是唯一的,因此非常适合id
返回data.isin;
},
onGridReady:setRowData($ http)
};

函数numberFormatter(params){
if(typeof params.value ==='number'){
return params.value.toFixed(4);
} else {
return params.value;
}
}



function BidRenderer(){}

BidRenderer.prototype.init = function(params) {
//创建单元格
this.eGui = document.createElement('div');
this.eGui.innerHTML =‘< div>< / div>’;

//将值设置到单元格
this.eValue = this.eGui.querySelectorAll(’div’)[0];
this.eValue.innerHTML = params.valueFormatted吗? params.valueFormatted:params.value;

};

//当网格准备插入元素
时被调用一次BidRenderer.prototype.getGui = function(){
返回this.eGui;
};

//每当用户获取单元格以刷新
时都会调用BidRenderer.prototype.refresh = function(params){
//再次将值设置到单元格
this.eGui.innerHTML ='< div class = bid>< / div>';;
this.eValue = this.eGui.querySelectorAll(’div’)[0];
this.eValue.innerHTML = params.valueFormatted吗? params.valueFormatted:params.value;

};

函数AskRenderer(){}

AskRenderer.prototype.init = function(params){
//创建单元格
this.eGui = document.createElement('div');
this.eGui.innerHTML =‘< div>< / div>’;

//将值设置到单元格
this.eValue = this.eGui.querySelectorAll(’div’)[0];
this.eValue.innerHTML = params.valueFormatted吗? params.valueFormatted:params.value;

};

//当网格准备插入元素
时被调用一次AskRenderer.prototype.getGui = function(){
返回this.eGui;
};

//每当用户获取单元格刷新时调用
AskRenderer.prototype.refresh = function(params){
//再次将值设置到单元格
this.eGui.innerHTML ='< div class = ask>< / div>';;
this.eValue = this.eGui.querySelectorAll(’div’)[0];
this.eValue.innerHTML = params.valueFormatted吗? params.valueFormatted:params.value;
};

//客户代码(即您的代码)将调用此构造函数,传入
//视口完成任务所需的任何内容
函数ViewportDatasource(mockServer){
this.mockServer =模拟服务器;
this.connectionId = this.mockServer.connect(this.eventListener.bind(this));
}

//被网格调用,告诉我们网格正在显示哪些行,因此
//我们需要时间告诉服务器为我们提供行显示范围
ViewportDatasource.prototype.setViewportRange =函数(firstRow,lastRow){
this.mockServer.setViewportRange(this.connectionId,firstRow,lastRow);
};

//由网格调用,为我们提供我们需要的回调
ViewportDatasource.prototype.init =函数(参数){
this.params = params;
};

//由网格调用,当网格被破坏或此数据源换出另一个
ViewportDatasource.prototype.destroy = function(){
this.mockServer。断开连接(this.connectionId);
};

//管理从服务器返回的事件
ViewportDatasource.prototype.eventListener =函数(事件){
开关(event.eventType){
case'rowCountChanged' :
this.onRowCountChanged(event);
休息时间;
案例 rowData:
this.onRowData(event);
休息时间;
案例 dataUpdated:
this.onDataUpdated(event);
休息时间;
}
};

//处理rowData事件
ViewportDatasource.prototype.onRowData =函数(事件){
var rowDataFromServer = event.rowDataMap;
this.params.setRowData(rowDataFromServer);
};

//处理dataUpdated事件
ViewportDatasource.prototype.onDataUpdated =函数(事件){
var that = this;
event.changes.forEach(function(change){
var rowNode = that.params.getRow(change.rowIndex);
//如果缺少rowNode,则表示网格为
//如果数据丢失,则表示rowNode在那,但是该数据尚未加载
//,所以请尽早设置增量更改。 $ b if(!rowNode ||!rowNode.data){
return;
}
// rowNode.data [change.columnId] = change.newValue;
//这是一个技巧,它使行刷新
rowNode.setDataValue(change.columnId,change.newValue);
});
};

//处理rowCount事件
ViewportDatasource.prototype.onRowCountChanged =函数(事件){
var rowCountFromServer = event.rowCount;
//将获得网格以设置行容器的高度,因此我们可以正确地垂直滚动
this.params.setRowCount(rowCountFromServer);
};

函数setRowData($ http){
//设置模拟服务器-实际代码不会执行此操作,它将与
//实际服务器联系以获取其内容需要
var mockServer = new MockServer();
$ http.get(‘data.json’)。then(function(response){
mockServer.init(response.data);
});

var viewportDatasource = new ViewportDatasource(mockServer);
table.api.setViewportDatasource(viewportDatasource);
//将'size cols to fit'放入超时,以便将滚动考虑在内
setTimeout(function(){
table.api.sizeColumnsToFit();
},100);
}

//在页面加载完毕后设置网格
/ * document.addEventListener('DOMContentLoaded',function(){
var gridDiv = document .querySelector('#liveStreamExample');
新的agGrid.Grid(gridDiv,table);

//执行http请求以获取示例数据-不使用任何框架来保存示例
//您可能会使用JQuery,Angular等框架进行HTTP调用
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET ','data.json');
httpRequest.send();
httpRequest.onreadystatechange = function(){
if(httpRequest.readyState == 4&& httpRequest.status == 200){
var httpResponse = JSON.parse(httpRequest.responseText);
setRowData(httpResponse);
}
};
}); * /

};

WatcherTable.prototype.getContextMenuItems =函数($ rootScope,params){
var result = [{name: Show Book,action:WatcherTable.prototype.changeBookSubscription.bind(this, $ rootScope,params.node.data)}];

返回结果;
}

WatcherTable.prototype.onCellDoubleClicked =函数($ rootScope,params){
$ rootScope。$ broadcast( changeBookSubscription,{instrkey:params.data.cus + 。 + params.data.isin,boardLabel:params.data.isd + + params.data.lbl});
if(params.colDef.field.indexOf( bBid)> -1){
$ rootScope。$ broadcast( showHitDialog,params);
log(显示点击对话框);
console.log(params);
}
else if(params.colDef.field.indexOf( bAsk)> -1){
$ rootScope。$ broadcast( showLiftDialog,params);
log(显示升降机对话框);
console.log(params);
}
}

WatcherTable.prototype.changeBookSubscription =函数($ rootScope,data){
$ rootScope。$ broadcast( changeBookSubscription,{instrkey:data .cus +。 + data.isin,boardLabel:data.isd + + data.lbl});
}

WatcherTable.prototype.getMainMenuItems = function($ rootScope,params){
var prcCols = [ bBidPrc, bAskPrc, oBidPrc, oAskPrc ];
var spdCols = [ bBidSpd, bAskSpd, oBidSpd, oAskSpd];
var menuItems = [
{name:'Show Price',
action:function(){
params.columnApi.setColumnsVisible(prcCols,!params.api.gridCore.gridOptions .showPrice);
params.api.gridCore.gridOptions.showPrice =!params.api.gridCore.gridOptions.showPrice;
},
已检查:params.api.gridCore.gridOptions.showPrice
},
{name:'Show Spread',
action:function(){
params.columnApi.setColumnsVisible(spdCols,!params.api.gridCore.gridOptions.showSpread);
params.api.gridCore.gridOptions.showSpread =!params.api.gridCore.gridOptions.showSpread;
},
已检查:params.api.gridCore.gridOptions.showSpread
},
{
名称: Orders,
子菜单:[
{name:'Live Order Only',
action:function(){
if(params.api.gridCore.gridOptions.orderFilter ==='live'){
参数.api.gridCore.gridOptions.orderFilter ='';
// TODO过滤器
}
else {params.api.gridCore.gridOptions.orderFilter ='live';
// TODO过滤器
}

},选中:(params.api.gridCore.gridOptions.orderFilter ==='live')},
{name :仅限我的订单,action:function(){
if(params.api.gridCore.gridOptions.orderFilter ==='mine'){
params.api.gridCore.gridOptions.orderFilter = '';
// TODO过滤器
}
else {params.api.gridCore.gridOptions.orderFilter ='mine';
// TODO过滤器
}

},选中:(params.api.gridCore.gridOptions.orderFilter ==='mine')},
{name :仅限我的公司订单,action:function(){
if(params.api.gridCore.gridOptions.orderFilter ==='firm'){
params.api.gridCore .gridOptions.orderFilter ='';
// TODO过滤器
}
else {params.api.gridCore.gridOptions.orderFilter = firm;
// TODO过滤器
}

},选中:(params.api.gridCore.gridOptions.orderFilter ==='firm')},
]
},
{name:'Size ...',action:function(){

console.log(params.api.gridCore.gridOptions.orderSize);
$ rootScope。$ broadcast( orderSizeDialog,{size:parseInt(params.api.gridCore.gridOptions.orderSize)});;
},
}
];
return menuItems;
}

你能帮我吗?



编辑



我注意到创建ViewportDatasource对象时未调用eventListener函数。我该如何强制呢?



编辑2



我取出了ViewportDatasource声明WatcherTable范围。现在我已经解决了开始的问题,但是我无法将数据加载到网格中。



我创建了一个插件: https://plnkr.co/edit/EEEJULRE72nbPF6G0PCK

解决方案

(从今天的问题出发,我想这里有类似的问题)



插拔器中存在计时问题-MockServer尝试在数据可用之前处理数据。 / p>

您需要做两件事来解决此问题-第一是仅在MockServer中的数据可用后才尝试设置数据源:

  WatcherTable.prototype.setRowData = function($ http){
//设置模拟服务器-实际代码不会这样做,它将联系您的
//真实服务器以获取所需的信息
var mockServer = new MockServer();
var that = this;
$ http.get('data.json')。then(function(response){
mockServer.init(response.data);
var viewportDatasource = new ViewportDatasource(mockServer);
that.table.api.setViewportDatasource(viewportDatasource);
//将 size cols to fit放入超时,以便将滚动考虑在内
setTimeout(function(){
that.table.api.sizeColumnsToFit();
},100);
});
}

第二,沿着同一主题,您需要防止尝试定期更新在准备好数据之前对其进行处理。在这里,您可以在数据可用后开始定期更新,或者更简单地在使用前添加支票:

  MockServer.prototype.periodicallyUpdateData = function(){
if(!this.allData)return;

我在这里分叉了您的朋克(经过上述更改): https://plnkr.co/edit/cY30aHIPydVOjcihX8Zh?p=preview


I'm replicating the ag-grid Viewport example putting it in an object representing the table instead of a anonymous function. I cannot understand why it gives me the error in the title when trying to connect to the mockserver, given that it is exactly the same code.

Here it is the code that doesn't seem to work:

   function ViewportDatasource(mockServer) {
        this.mockServer = mockServer;
        this.connectionId = this.mockServer.connect(this.eventListener.bind(this));
    }

    ViewportDatasource.prototype.eventListener = function (event) {
        switch (event.eventType) {
            case 'rowCountChanged':
                this.onRowCountChanged(event);
                break;
            case 'rowData':
                this.onRowData(event);
                break;
            case 'dataUpdated':
                this.onDataUpdated(event);
                break;
        }
    };

here it is the whole object:

function WatcherTable($rootScope,$scope, $http) {

    this.FIELD_KEY_ID = "id";
    this.FIELD_KEY_ISSUER_SHORT_DESC= "isd";
    this.FIELD_KEY_ISSUER = "iss";
    this.FIELD_KEY_CUSIP = "cus";
    this.FIELD_KEY_ISIN = "isin";
    this.FIELD_KEY_BOARD_LABEL = "lbl";
    this.FIELD_KEY_IND_SECT_LABEL = "isl";
    this.FIELD_KEY_CURR="cur"

    this.FIELD_KEY_BEST_BID_SIZE = "bBidSz";
    this.FIELD_KEY_BEST_BID_PRICE = "bBidPrc";
    this.FIELD_KEY_BEST_ASK_PRICE = "bAskPrc";
    this.FIELD_KEY_BEST_ASK_SIZE = "bAskSz";
    this.FIELD_KEY_BEST_BID_SPREAD = "bBidSpd";
    this.FIELD_KEY_BEST_ASK_SPREAD = "bAskSpd";

    this.FIELD_KEY_ORDER_BID_SIZE = "oBidSz";
    this.FIELD_KEY_ORDER_BID_PRICE = "oBidPrc";
    this.FIELD_KEY_ORDER_ASK_PRICE = "oAskPrc";
    this.FIELD_KEY_ORDER_ASK_SIZE = "oAskSz";
    this.FIELD_KEY_ORDER_BID_SPREAD = "oBidSpd";
    this.FIELD_KEY_ORDER_ASK_SPREAD = "oAskSpd";

    this.headerMyOrder="ORDER";
    this.headerMyBidOrder="BID ORDER";
    this.headerMyAskOrder="ASK ORDER";


    this.cols = [{
        headerName : "Security Info",
        marryChildren : true,
        children : [{
            headerName : "Issuer Short Desc.",
            field : this.FIELD_KEY_ISSUER_SHORT_DESC,

            //width : 0,
            //hide : true
        },
        {
            headerName : "Industry Sector Label",
            field : this.FIELD_KEY_IND_SECT_LABEL,
            //width : 80,
            filter: 'set',
            filterParams: { values: ['Advertising', 'Aerospace/Defense', 'Agriculture', 'Airlines', 'Apparel', 'Auto Manufacturers', 'Auto Parts&Equipment', 'Banks', 'Basic Materials', 'Beverages', 'Biotechnology', 'Building Materials', 'Chemicals', 'Coal', 'Commercial Services', 'Communications', 'Computers', 'Consumer, Cyclical', 'Consumer, Non-cyclical', 'Cosmetics/Personal Care', 'Distribution/Wholesale', 'Diversified', 'Electrical Compo&Equip', 'Electronics', 'Energy', 'Energy-Alternate Sources', 'Engineering&Construction', 'Entertainment', 'Machinery-Constr&Mining', 'Household Products/WaresIndustrial', 'Insurance', 'Internet', 'Investment Companies', 'Iron/Steel', 'Kangaroos', 'Leisure Time', 'Lodging', 'Machinery-Constr&Mining', 'Machinery-Diversified', 'Media', 'Metal Fabricate/Hardware', 'Mining', 'Miscellaneous Manufactur', 'Multi-National', 'Office Furnishings', 'Office/Business ', 'Oil&Gas', 'Oil&Gas Services', 'Packaging&Containers', 'Pharmaceuticals', 'Pipelines', 'Real Estate', 'Regional(state/provnc)', 'REITS', 'Retail', 'Savings&Loans'],
                            newRowsAction: 'keep'},
            },
        {
            headerName : "Board Label",
            field : this.FIELD_KEY_BOARD_LABEL,
            //width : 80,
            filter: 'text',
            filterParams: { apply: true }

        }, {
            headerName : "CUSIP",
            field : this.FIELD_KEY_CUSIP,
            //width : 150,
            //suppressFilter: true
        },
        {
            headerName : "ISIN",
            field : this.FIELD_KEY_ISIN,
            //width : 150,
            //suppressFilter: true
        },
        {
            headerName : "Currency",
            field : this.FIELD_KEY_CURR,
            //width : 150,
            //suppressFilter: true
        }
        ]},
        {
        headerName : "Best",
        marryChildren : true,

        children : [ {
            headerName : "Bid Size",
            pinned: 'right',
            field : this.FIELD_KEY_BEST_BID_SIZE,
            cellStyle: {'border-left': '1px solid #E82043', 'color':'#E82043', 'font-weight':'bold', 'text-align':'right'},
            cellRenderer: BidRenderer,
            filter:'number',


            //width : 125,
            //suppressFilter: true
        }, {
            headerName : "Bid Price",
            pinned: 'right',
            field : this.FIELD_KEY_BEST_BID_PRICE,
            cellStyle: {'border-right': '1px solid #E82043', 'color':'#E82043', 'font-weight':'bold', 'text-align':'right'},
            //cellRenderer: 'animateShowChange',
            cellFormatter: numberFormatter,
            cellRenderer: BidRenderer,
            width : 125,
            filter:'number',


            //suppressFilter: true
        },
        {
            headerName : "Ask Price",
            pinned: 'right',
            field : this.FIELD_KEY_BEST_ASK_PRICE,
            //cellRenderer: 'animateShowChange',
            cellFormatter: numberFormatter,
            cellRenderer: AskRenderer,
            cellStyle: {'color':'#19B092', 'font-weight':'bold', 'text-align':'right'},
            filter:'number',
            //width : 125,
            //suppressFilter: true
        },
        {
            headerName : "Ask Size",
            pinned: 'right',
            field : this.FIELD_KEY_BEST_ASK_SIZE,
            cellStyle: {'border-right': '1px solid #19B092', 'color':'#19B092', 'font-weight':'bold', 'text-align':'right'},
            cellRenderer: AskRenderer,
            filter:'number',
            //width : 125,
            //suppressFilter: true
        } ]
    } ];


    //definizione della tabella//// rowModelType: 'virtual', rowModelType: 'pagination',



    this.table = {
            showPrice: true,
            showSpread: true,
            orderSize: 0,
            orderFilter: '',
            enableServerSideFilter: true,
            enableServerSideSorting: true,
            sortingOrder: ['desc','asc',null],
            enableColResize : true,
            debug : true,
            rowSelection : 'multiple',
            rowDeselection : true,
            columnDefs : this.cols,
            rowModelType : 'viewport',
            headerHeight: 20,
            rowHeight: 20,
            viewportRowModelPageSize:30,
            viewportRowModelBufferSize: 15,         
            suppressColumnVirtualisation: true, 
            suppressMenuColumnPanel: true,
            onCellDoubleClicked: WatcherTable.prototype.onCellDoubleClicked.bind(this,$rootScope),          
            getContextMenuItems: WatcherTable.prototype.getContextMenuItems.bind(this,$rootScope),
            getMainMenuItems: WatcherTable.prototype.getMainMenuItems.bind(this, $rootScope), 
            getRowNodeId: function (data) {
                // the code is unique, so perfect for the id
                return data.isin;
            },
            onGridReady:setRowData($http)
    };

    function numberFormatter(params) {
        if (typeof params.value === 'number') {
            return params.value.toFixed(4);
        } else {
            return params.value;
        }
    }



    function BidRenderer () {}

    BidRenderer.prototype.init = function(params) {
        // create the cell
        this.eGui = document.createElement('div');
        this.eGui.innerHTML = '<div></div>';

        // set value into cell
        this.eValue = this.eGui.querySelectorAll('div')[0];
        this.eValue.innerHTML = params.valueFormatted ? params.valueFormatted : params.value;

    };

    // gets called once when grid ready to insert the element
    BidRenderer.prototype.getGui = function() {
        return this.eGui;
    };

    // gets called whenever the user gets the cell to refresh
    BidRenderer.prototype.refresh = function(params) {
        // set value into cell again
        this.eGui.innerHTML = '<div class="bid"></div>';
        this.eValue = this.eGui.querySelectorAll('div')[0];
        this.eValue.innerHTML = params.valueFormatted ? params.valueFormatted : params.value;

    };

    function AskRenderer () {}

    AskRenderer.prototype.init = function(params) {
        // create the cell
        this.eGui = document.createElement('div');
        this.eGui.innerHTML = '<div></div>';

        // set value into cell
        this.eValue = this.eGui.querySelectorAll('div')[0];
        this.eValue.innerHTML = params.valueFormatted ? params.valueFormatted : params.value;

    };

    // gets called once when grid ready to insert the element
    AskRenderer.prototype.getGui = function() {
        return this.eGui;
    };

    // gets called whenever the user gets the cell to refresh
    AskRenderer.prototype.refresh = function(params) {
        // set value into cell again
        this.eGui.innerHTML = '<div class="ask"></div>';
        this.eValue = this.eGui.querySelectorAll('div')[0];
        this.eValue.innerHTML = params.valueFormatted ? params.valueFormatted : params.value;
    };

    // client code (ie your code) will call this constructor, pass in whatever you need for the
    // viewport to do it's job
    function ViewportDatasource(mockServer) {
        this.mockServer = mockServer;
        this.connectionId = this.mockServer.connect(this.eventListener.bind(this));
    }

    // gets called by the grid, tells us what rows the grid is displaying, so time for
    // us to tell the server to give us the rows for that displayed range
    ViewportDatasource.prototype.setViewportRange = function (firstRow, lastRow) {
        this.mockServer.setViewportRange(this.connectionId, firstRow, lastRow);
    };

    // gets called by the grid, provides us with the callbacks we need
    ViewportDatasource.prototype.init = function (params) {
        this.params = params;
    };

    // gets called by grid, when grid is destroyed or this datasource is swapped out for another one
    ViewportDatasource.prototype.destroy = function () {
        this.mockServer.disconnect(this.connectionId);
    };

    // manages events back from the server
    ViewportDatasource.prototype.eventListener = function (event) {
        switch (event.eventType) {
            case 'rowCountChanged':
                this.onRowCountChanged(event);
                break;
            case 'rowData':
                this.onRowData(event);
                break;
            case 'dataUpdated':
                this.onDataUpdated(event);
                break;
        }
    };

    // process rowData event
    ViewportDatasource.prototype.onRowData = function (event) {
        var rowDataFromServer = event.rowDataMap;
        this.params.setRowData(rowDataFromServer);
    };

    // process dataUpdated event
    ViewportDatasource.prototype.onDataUpdated = function (event) {
        var that = this;
        event.changes.forEach(function (change) {
            var rowNode = that.params.getRow(change.rowIndex);
            // if the rowNode is missing, it means the grid is not displaying that row.
            // if the data is missing, it means the rowNode is there, but that data has not
            // loaded into it yet, so to early to set delta changes.
            if (!rowNode || !rowNode.data) {
                return;
            }
            // rowNode.data[change.columnId] = change.newValue;
            // this is a trick, it gets the row to refresh
            rowNode.setDataValue(change.columnId, change.newValue);
        });
    };

    // process rowCount event
    ViewportDatasource.prototype.onRowCountChanged = function (event) {
        var rowCountFromServer = event.rowCount;
        // this will get the grid to make set the height of the row container, so we can scroll vertically properly
        this.params.setRowCount(rowCountFromServer);
    };

    function setRowData($http) {
        // set up a mock server - real code will not do this, it will contact your
        // real server to get what it needs
        var mockServer = new MockServer();
        $http.get('data.json').then(function(response){
            mockServer.init(response.data);
        });

        var viewportDatasource = new ViewportDatasource(mockServer);
        table.api.setViewportDatasource(viewportDatasource);
        // put the 'size cols to fit' into a timeout, so that the scroll is taken into consideration
        setTimeout(function () {
            table.api.sizeColumnsToFit();
        }, 100);
    }

    // setup the grid after the page has finished loading
   /* document.addEventListener('DOMContentLoaded', function () {
        var gridDiv = document.querySelector('#liveStreamExample');
        new agGrid.Grid(gridDiv, table);

        // do http request to get our sample data - not using any framework to keep the example self contained.
        // you will probably use a framework like JQuery, Angular or something else to do your HTTP calls.
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', 'data.json');
        httpRequest.send();
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                var httpResponse = JSON.parse(httpRequest.responseText);
                setRowData(httpResponse);
            }
        };
    });*/

};

WatcherTable.prototype.getContextMenuItems = function ($rootScope,params){
    var result= [{name:"Show Book", action:WatcherTable.prototype.changeBookSubscription.bind(this,$rootScope,params.node.data)}];

    return result;
}

WatcherTable.prototype.onCellDoubleClicked = function ($rootScope,params){
    $rootScope.$broadcast("changeBookSubscription",{instrkey:params.data.cus+"."+params.data.isin,boardLabel:params.data.isd+" "+params.data.lbl});
    if(params.colDef.field.indexOf("bBid")>-1){
        $rootScope.$broadcast("showHitDialog",params);
        log("Show hit dialog");
        console.log(params);
    }
    else if(params.colDef.field.indexOf("bAsk")>-1){
        $rootScope.$broadcast("showLiftDialog",params);
        log("Show lift dialog");
        console.log(params);
    }
}

WatcherTable.prototype.changeBookSubscription = function ($rootScope,data) {
    $rootScope.$broadcast("changeBookSubscription",{instrkey:data.cus+"."+data.isin,boardLabel:data.isd+" "+data.lbl});
}

WatcherTable.prototype.getMainMenuItems = function($rootScope, params){
    var prcCols=["bBidPrc","bAskPrc","oBidPrc","oAskPrc"];
    var spdCols=["bBidSpd","bAskSpd","oBidSpd","oAskSpd"];
    var menuItems= [
        {name:'Show Price', 
            action:function(){
                        params.columnApi.setColumnsVisible(prcCols, !params.api.gridCore.gridOptions.showPrice);
                        params.api.gridCore.gridOptions.showPrice= !params.api.gridCore.gridOptions.showPrice;      
                    }, 
             checked: params.api.gridCore.gridOptions.showPrice
             },
        {name:'Show Spread', 
        action:function(){
                    params.columnApi.setColumnsVisible(spdCols, !params.api.gridCore.gridOptions.showSpread);
                    params.api.gridCore.gridOptions.showSpread= !params.api.gridCore.gridOptions.showSpread;        
                }, 
         checked: params.api.gridCore.gridOptions.showSpread
         },
         {
             name:'Orders',
                subMenu:[
                    {name:'Live Orders Only', 
                        action:function(){
                        if (params.api.gridCore.gridOptions.orderFilter==='live'){
                            params.api.gridCore.gridOptions.orderFilter='';
                            //TODO filter
                        }
                        else {params.api.gridCore.gridOptions.orderFilter='live';
                            //TODO filter
                        }

                    }, checked:(params.api.gridCore.gridOptions.orderFilter==='live')},
                    {name:'My Orders Only',     action:function(){
                        if (params.api.gridCore.gridOptions.orderFilter==='mine'){
                            params.api.gridCore.gridOptions.orderFilter='';
                            //TODO filter
                        }
                        else {params.api.gridCore.gridOptions.orderFilter='mine';
                            //TODO filter
                        }

                    }, checked:(params.api.gridCore.gridOptions.orderFilter==='mine')},
                    {name:'My Firm\'s Orders Only', action:function(){
                        if (params.api.gridCore.gridOptions.orderFilter==='firm'){
                            params.api.gridCore.gridOptions.orderFilter='';
                            //TODO filter
                        }
                        else {params.api.gridCore.gridOptions.orderFilter='firm';
                            //TODO filter
                        }

                    }, checked:(params.api.gridCore.gridOptions.orderFilter==='firm')},
                ]
         },
         {name: 'Size ...', action: function() {

             console.log(params.api.gridCore.gridOptions.orderSize);
             $rootScope.$broadcast("orderSizeDialog",{size:parseInt(params.api.gridCore.gridOptions.orderSize)});
            },
            }
    ];
    return menuItems;
}

Can you help me?

EDIT

I noticed that eventListener function isn't being called when creating ViewportDatasource object. How can I force it?

EDIT 2

I took ViewportDatasource declaration out of WatcherTable scope. Now I got over the starting issue, but I cannot load data into the grid.

I created a plunker: https://plnkr.co/edit/EEEJULRE72nbPF6G0PCK

解决方案

(Taken from your question today, similar problems here I think)

You have a timing issue in your plunker - your MockServer is trying to process data before it's available.

You need to do two things to resolve this - the first is to only try set the data source once the data is available in the MockServer:

WatcherTable.prototype.setRowData = function ($http) {
    // set up a mock server - real code will not do this, it will contact your
    // real server to get what it needs
    var mockServer = new MockServer();
    var that = this;
    $http.get('data.json').then(function (response) {
        mockServer.init(response.data);
        var viewportDatasource = new ViewportDatasource(mockServer);
        that.table.api.setViewportDatasource(viewportDatasource);
        // put the 'size cols to fit' into a timeout, so that the scroll is taken into consideration
        setTimeout(function () {
            that.table.api.sizeColumnsToFit();
        }, 100);
    });
}

Secondly, along the same theme, you need to prevent the periodic updates from trying to process data before its ready. Here you can either kick off the periodical updates AFTER the data is available, or more simply add a check before you try use it:

MockServer.prototype.periodicallyUpdateData = function() {
    if(!this.allData) return;

I've forked your plunker (with the above changes) here: https://plnkr.co/edit/cY30aHIPydVOjcihX8Zh?p=preview

这篇关于Ag-grid视口:无法读取未定义的属性“ bind”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆