0

我正在使用 Windows 8.1 winJS,并尝试从 indexedb 填充 listView 并且无法使其工作。我从 jsonStr 第 76 行得到一个字符串,但我无法绑定到 html。

我的 javascript

(function () {

"use strict";

var nav = WinJS.Navigation;
var session = WinJS.Application.sessionState;
var util = WinJS.Utilities;

WinJS.Namespace.define("DataExampleA",
    {
        itemList: new WinJS.Binding.List()
    })

var plantsData1 = [

{ id: 1, title: "Banana blast1", text: "Ice cream", picture: "images/plants/Acalypha pendula.jpg" },
{ id: 2, title: "Banana blast2", text: "Ice cream", picture: "images/plants/Acalypha pendula.jpg" },
{ id: 3, title: "Banana blast3", text: "Ice cream", picture: "images/plants/Acalypha pendula.jpg" }
];

var indexedDB = window.msIndexedDB;
var IDBTransaction = window.IDBTransaction;

if (!window.indexedDB) {
    window.console.log("Your browser doesn't support a stable version of IndexedDB.")
}

var db;
var request = window.msIndexedDB.open("plantsDatabase", 1);

request.onerror = function (event) {
    console.log("error: ");
};

request.onsuccess = function (event) {
    db = request.result;
    console.log("success: " + db);
};

request.onupgradeneeded = function (event) {
    console.log('Creating object stores');
    var db = event.target.result;
    var objectStore = db.createObjectStore("plantsStore", { keyPath: "id" });
    for (var i in plantsData1) {
        objectStore.add(plantsData1[i]);
    }
}

function read() {
    var transaction = db.transaction(["plantsStore"]);
    var objectStore = transaction.objectStore("plantsStore");
    var request = objectStore.get("00-03");
    request.onerror = function (event) {
        console.log("Unable to retrieve daa from database!");
    };
    request.onsuccess = function (event) {
        // Do something with the request.result!
        if (request.result) {

            // console.log("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);
        } else {
            console.log("Kenny couldn't be found in your database!");
        }
    };
}

function buttonreadAll(plantsBind) {
    var transaction = db.transaction(["plantsStore"]);
    var objectStore = transaction.objectStore("plantsStore");


    objectStore.openCursor().onsuccess = function (event) {
        var cursor = event.target.result;

        if (cursor) {

            var plantsBind = cursor.value;
            var jsonStr = JSON.stringify(plantsBind);
            console.log(jsonStr);
            var dataList = new WinJS.Binding.List(cursor.value);
            // Create a namespace to make the data publicly accessible. 
            var publicMembers =
                {
                   itemList: dataList

                };
            WinJS.Namespace.define("DataExampleA", publicMembers);

            cursor.continue();
        }
        else {
            console.log("No more entries!");
        }
    };
}



WinJS.UI.Pages.define("/pages/hub/hub.html", {
    processed: function (element) {
        return WinJS.Resources.processAll(element);
    },

    // This function is called whenever a user navigates to this page. It
    // populates the page elements with the app's data.
    ready: function (element, options) {

        var readAll = document.getElementById("readAll");
        readAll.addEventListener("click", buttonreadAll, false);

    },


    unload: function () {
        // TODO: Respond to navigations away from this page.
    },

    updateLayout: function (element) {
        /// <param name="element" domElement="true" />

        // TODO: Respond to changes in layout.



    },
});




})();

和我的html

<div class="section3" data-win-control="WinJS.UI.HubSection" data-win-options="{ isHeaderStatic: true }" data-win-res="{ winControl: {'header': 'Section3'} }">
                  <div id="IconTextTemplate1" class="win-container win-itembox win-item" data-win-control="WinJS.Binding.Template">
                    <div style=" padding: 5px; overflow: hidden; display: -ms-grid;">
                        <img data-win-bind="alt: title; src: picture" src="#" style="width: 80%;  margin-left: 10%; margin-right:10%; margin-bottom:2%; -ms-grid-column: 1;" />
                        <div style="margin: 15px; -ms-grid-row: 2">
                            <h3 data-win-bind="innerText: title"></h3>
                            <h3 data-win-bind="innerText: picture"></h3>
                            <h6 data-win-bind="innerText: text"></h6>
                        </div>
                    </div>
                </div>
                <div id="basicListView" data-win-control="WinJS.UI.ListView"
                     data-win-options="{
                     itemDataSource : DataExampleA.itemList.dataSource,
                     itemTemplate: select('#IconTextTemplate1'),
                     layout : {type: WinJS.UI.GridLayout}}">
                </div> 
                </div>
4

3 回答 3

1

要添加到 Kristof 的响应中,您需要替换此代码:

var dataList = new WinJS.Binding.List(cursor.value);
// Create a namespace to make the data publicly accessible. 
var publicMembers =
    {
    itemList: dataList

};
WinJS.Namespace.define("DataExampleA", publicMembers);

仅此行,因为您已经创建了一个列表:

DataExampleA.itemList.push(cursor.value);

我在一个项目中对此进行了尝试,效果很好。

那么问题是当您向数据库添加内容时如何让 ListView 自行更新。答案是,如果您向 DataExampleA.itemList 添加一个项目,ListView 绑定到该项目,这将更新 ListView。这意味着您需要有一个例程来在数据库更改时更新列表,基本上在应用程序运行时保持两者并行。当然,当应用程序重新启动时,您将从数据库中重新初始化 Binding.List,以便它们同步启动。

您可以采取的另一种方法是在 IndexedDB 之上创建一个自定义数据源,您可以通过使用IListDataAdapter接口方法的某些部分来实现一个对象,然后使用它来创建一个WinJS.UI.VirtualizedDataSource。这需要做更多的工作,但如果您预计数据集较大,则可以更好地扩展。有关这方面的更多信息,请参阅我的第二本预览电子书(免费)的第 7 章,在“收集控制数据源”部分中。

于 2013-10-31T16:48:19.950 回答
0

您正在为您检索的每个项目创建一个新列表。

使用 push 方法将新项目添加到 listview 集合中。

我不是 100% 确定这会奏效。我也尝试了一段时间,但没有按照我想要的方式工作。我相信我遇到的问题是当我添加数据时没有触发事件,这样它们就没有被可视化。

于 2013-10-31T09:30:39.397 回答
0

不要使用全局 db 变量。

于 2013-10-31T21:06:17.980 回答