从Indexeddb填充ListView

时间:2013-10-31 05:54:16

标签: javascript winjs indexeddb windows-8.1

我正在使用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>

3 个答案:

答案 0 :(得分: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);

只有这一行,因为你已经创建了一个List:

DataExampleA.itemList.push(cursor.value);

我在一个项目中试过这个并且它运行得很好。

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

您可以采用的另一种方法是在IndexedDB之上创建自定义数据源,您可以通过使用IListDataAdapter接口方法的某些部分实现对象,然后使用它创建{{ 3}}。这是一个更多的工作,但如果您预期大型数据集将更好地扩展。有关详细信息,请参阅我的WinJS.UI.VirtualizedDataSource第7章,&#34;收集控制数据源。&#34;

答案 1 :(得分:0)

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

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

我不是100%确定这会起作用。我已经尝试了一段时间,并没有按照我想要的方式工作。我认为我遇到的问题是,当我添加数据时,事件没有被触发,这样他们就没有可视化。

答案 2 :(得分:0)

不要使用全局db变量。