如何在javascript中的类变量中存储函数?

时间:2015-05-11 08:14:17

标签: javascript

我想创建一个用于在网页上操作列表视图功能的类。但我找到ListViewSelectedIndexChange的解决方案有问题(你知道它的用途)。实际上我无法存储稍后调用的函数。

这是我的代码。

ListView = function (listViewID) {
    //unique listview id
    this.ID = listViewID;

    //event hanadler
    var SelectedIndexChanged: function = {};
    this.onSelectedIndexChanged = function (fn) { this.SelectedIndexChanged = fn;};
    //adds an item to listview
    this.addItem = function (items, itemTag) {
        var listViewTable = $("#" + this.ID + " table")[0];
        var itemsCount = items.length;
        var itemID = this.ID + "_" + Math.floor(Math.random() * 10000);
        var trString = "<tr id=\"" + itemID + "\">";
        for (i = 0; i < itemsCount; i++) {
            trString += "<td>" + items[i] + "</td>";
        }
        trString += "<td class=\"tag\"";
        trString += "</tr>";
        var newRow = $(trString);
        (function (eventHandler) {
            $(newRow).bind("click", function () { eventHandler(); });
        })(this.SelectedIndexChanged);

        $(listViewTable).append(newRow);
    }

    //returns number of items in the listview
    this.itemsCount = function () {
        var listViewTable = $("#" + this.ID + " table")[0];
        return $(listViewTable).find("tr").length - 1;
    }
    //removes the listview from DOM
    this.remove = function () {
        $("#" + this.ID).remove();
    }
}

我用这种方式。

var listView = new ListView(listViewID);
listView.addItem(["1", "2", "3"], "3");
listView.onSelectedIndexChanged = function () { alert("event fired"); };

但它不起作用。因为只有  原来的空函数将被执行。

1 个答案:

答案 0 :(得分:0)

var SelectedIndexChanged: function = {};更改为var SelectedIndexChanged: function() {};