1

我有一个使用列表的 WinRT/javaScript 应用程序。作为测试,我有以下代码:

var testList = new WinJS.Binding.List();
var item = {
    key: "mykey",
    value: "hello",
    value2: "world"
};

testList.push(item);

var foundItem = testList.getItemFromKey("mykey");

我希望能够使用提供的密钥找到我的物品;但是foundItem总是返回未定义。在设置和使用我的列表时我做错了什么吗?

此外,当我在调试时检查我的列表时,我可以看到我推送的项目的键是“1”而不是“mykey”。

4

1 回答 1

1

您要推送的是列表中对象的值,键在内部分配为递增的整数值。如果您base.js在项目中打开 Windows Library for JavaScript 1.0 参考资料,您将看到以下针对push.

注意对 的调用this._assignKey()。该值在oniteminserted处理程序中返回给您

push: function (value) {
    /// <signature helpKeyword="WinJS.Binding.List.push">
    /// <summary locid="WinJS.Binding.List.push">
    /// Appends new element(s) to a list, and returns the new length of the list.
    /// </summary>
    /// <param name="value" type="Object" parameterArray="true" locid="WinJS.Binding.List.push_p:value">The element to insert at the end of the list.</param>
    /// <returns type="Number" integer="true" locid="WinJS.Binding.List.push_returnValue">The new length of the list.</returns>
    /// </signature>
    this._initializeKeys();
    var length = arguments.length;
    for (var i = 0; i < length; i++) {
        var item = arguments[i];
        if (this._binding) {
            item = WinJS.Binding.as(item);
        }
        var key = this._assignKey();
        this._keys.push(key);
        if (this._data) {
            this._modifyingData++;
            try {
                this._data.push(arguments[i])
            } finally {
                this._modifyingData--;
            }
        }
        this._keyMap[key] = { handle: key, key: key, data: item };
        this._notifyItemInserted(key, this._keys.length - 1, item);
    }
    return this.length;
},

因此,如果您将以下内容添加到代码中,您将获得稍后可以使用的值(假设您将其与您推送的“键”相关联)。

testList.oniteminserted = function (e) {
    var newKey = e.detail.key;
};
于 2013-03-03T16:37:44.120 回答