我有一个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
总是返回undefined。我在设置和使用我的列表中做错了什么吗?
此外,当我在调试时检查列表时,我可以看到我推送的项的键是"1"而不是"mykey"。"
您正在推入的是列表中对象的值,键在内部分配为递增整数值。如果你在你的项目中打开Windows Library for JavaScript 1.0 reference中的base.js
,你会看到以下push
的实现。
注意对this._assignKey()
的调用。该值在oniteminserts处理程序
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;
};