在骨干同步中填充主干集合

时间:2014-01-28 15:33:02

标签: javascript backbone.js

如何在骨干同步中填充骨干集合,使得结果集合可以在骨干同步之外使用。

以下是一个例子:

mycollection = new MyCollection();
mycollection.fetch();

// after a few seconds ... it triggers the success function

mycollection.length; //prints 0 :S

这是我的骨干同步代码:

define(["backbone"], function (bb) {
        bb.sync = function (method, model, options) {

            var sql = "";

            if (!model.tabla) {
                if (options && options.error)
                    options.error("No property 'tabla' for model");
            }

            switch (method) {
                case 'create':
                    break;
                case 'update':
                    break;
                case 'delete':
                    break;
                case 'read':
                    sql = "select * from " + model.tabla;
                    break;
            }

            console.log("MODELO", model);

            if (app.db == undefined) return;

            app.db.transaction(function (tx) {
                tx.executeSql(sql, [], function (tx, res) {
                        var resp = [];
                        for (var i = 0; i < res.rows.length; i++) {
                            resp.push(res.rows.item(i));
                        }

                        if (options && options.success) options.success(resp);
                    }
                );
            }, function (e) {
                console.log(e);

                if (options && options.error) options.error(e);
            });
        }
    }
);

我的问题是输入模型没有被结果数组修改。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

收集的新数据仅在成功回调后才可用,因为您的情况下是异步调用。

您可以使用

mycollection.fetch().then(function() {
    console.log(mycollection.length);
});

或者

mycollection.fetch({
    success: function() {
        console.log(mycollection.length);
    }
});

甚至

mycollection.on("fetch-complete", function() {
    console.log(mycollection.length);
});

mycollection.fetch({
    success: function(collection) {
        collection.trigger("fetch-complete");
    }
});
相关问题