简体   繁体   English

仪表板列表-OnClick

[英]Dashcode List - OnClick

I have created a project in Dashcode, inserted a List control, enabled a dynamic list, created a JSON object and associated it with the control. 我已经在Dashcode中创建了一个项目,插入了一个List控件,启用了动态列表,创建了一个JSON对象并将其与该控件相关联。 The code looks like this ... 代码看起来像这样...

var stations = {

    _rowData: ["Mitchelton", "Gaythorne", "Albion", "Central", 
    "Burpengary", "Petrie", "Morayfield", "Caboolture", "Ferny Grove"],

    numberOfRows: function() { return this._rowData.length; },

    prepareRow: function(rowElement, rowIndex, templateElements) {
        if (templateElements.label) {
            templateElements.label.innerText = this._rowData[rowIndex];
        }
        rowElement.onclick = function(event) { alert("Row "+rowIndex); };
    }

As you can see when an item is selected it will print the rowIndex, but I would like to display the actual value at that index. 如您所见,当选择一个项目时,它将打印rowIndex,但我想显示该索引的实际值。

Unfortunately this (for example) "this._rowData[2]" doesnt work, it doesn't seem to be able to find the "_rowData" object. 不幸的是,这个(例如)“ this._rowData [2]”不起作用,它似乎无法找到“ _rowData”对象。

This should work: 这应该工作:

prepareRow: function(rowElement, rowIndex, templateElements) {
    if (templateElements.label) {
        templateElements.label.innerText = this._rowData[rowIndex];
    }

    var _this = this;
    rowElement.onclick = function(event) { alert(_this._rowData[2]); };
}

The problem is that within the rowElement.onclick event handler, this refers to the DOM element rowElement , not your stations object. 问题是在rowElement.onclick事件处理程序内, this是指DOM元素rowElement ,而不是您的stations对象。 We fix the problem by creating a variable (I've named it _this , but you can call it whatever you want) that points to the stations object and then using this variable whenever we want to access the stations object inside the event handler. 我们通过创建一个指向stations对象的变量(我将其命名为_this ,但是您可以随意调用它)来解决该问题,然后在每次要访问事件处理程序内部的stations对象时使用此变量。

See the following two articles for more information on the this keyword: 有关this关键字的更多信息,请参见以下两篇文章:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM