代码之家  ›  专栏  ›  技术社区  ›  bugfixr

WinJS.Binding.List-找不到键值

  •  1
  • bugfixr  · 技术社区  · 12 年前

    我有一个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”

    1 回复  |  直到 12 年前
        1
  •  1
  •   Jim O'Neil    12 年前

    您正在推动的是列表中对象的值,该键在内部分配为一个递增的整数值。如果你打开 base.js 在项目中的WindowsLibraryforJavaScript1.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;
    };