1

在获取我正在使用的骨干集合时,我遇到了一个奇怪的问题。在我的代码的一个特定实例中,我执行了一次提取(在代码的其他区域中我是如何做的,一切正常),提取似乎永远不会到达服务器,并且开发人员工具将请求显示为红色,并带有状态/文本字段中的单词(已取消)。

我已经将它引入了主干同步方法,我看到 $.ajax 正在构建,一切看起来都很好。有没有人遇到过这个问题?

如果有帮助,这是我的代码,这是一个调用两个 .ashx 服务以首先检查文件是否存在然后打开它的函数。对我不起作用的部分是“me.collection.fetch()。

openDocument: function () {
        var me = this,
                fileId = me.model.get('id'),
            userId = Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
            fileRequest = '/genericHandlers/DownloadFile.ashx?id=' + fileId + '&userId=' + userId,
            fileCheck = '/genericHandlers/CheckFileExistance.ashx?id=' + fileId + '&userId=' + userId;

        //hide tooltip
        me.hideButtonTooltips();

        // Check for file existance
        $.ajax({
            url: fileCheck
        })
        .done(function (data) {
            if (data && data === "true") {

                document.location.href = fileRequest;

                me.collection.fetch();



            } else if (!!data && data === "false") {
                "This file is no longer available.".notify('error');
            }
        })
        .fail(function (data) {
            "Something went wrong during the File Existance check".notify('error');
            "Something went wrong during the File Existance check".log(userId, 'error', 'Docs');
        });
    },

我的收藏:

// docsCollection.js - The collection of ALL the documents available to a given user

// Document Collection
Dashboard.Collections.DocsCollection = Backbone.Collection.extend({

    model: Dashboard.Models.DocumentUploadModel,

    url: function () {
        return 'apps/docs/Docs/' + this.userId;
    },

    initialize: function (options) {
        this.userId = options.userId;
        this.deferredFetch = this.fetch();

    },

    comparator: function (model) {
        return -(new Date(model.get('expirationDate')));
    },

    getDaysSinceViewedDocuments: function () { 
        return this.filter(function (model) {
            return model.get('daysSinceViewed') !== null;
        });
    },

    getNewDocuments: function () { 
        return this.filter(function (model) {
            return model.get('isNew');
        });
    },

    getExpiredDocuments: function () { 
        return this.filter(function (model) {
            return model.get('isExpired');
        });
    }

});

和我的模型:

Dashboard.Models.DocumentUploadModel = Backbone.Model.extend({
    defaults: {
        fileArray: [],
        name: '',
        description: '',
        accesses: [],
        tags: [],
        expirationDate: ''
    },

    initialize: function () {

            this.set({
                userId: Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
                expirationDate: (this.isNew()) ? buildExpirationDate() : this.get('expirationDate')
            }, { silent: true });

        function buildExpirationDate() {
            var date = new Date((new Date()).getTime() + 24 * 60 * 60 * 1000 * 7),
                    dateString = "{0}/{1}/{2}".format(date.getMonth() + 1, date.getDate(), date.getFullYear());

            return dateString;
        }

    },

    firstFile: function () {
        return this.get('fileArray')[0];
    },

    validate: function (attributes) {
        var errors = [];

        if (attributes.name === '' || attributes.name.length === 0)
            errors.push({
                input: 'input.txtName',
                message: "You must enter a name."
            });

        if (attributes.description === '' || attributes.description.length === 0)
            errors.push({
                input: 'textarea.taDescription',
                message: "You must enter a description."
            });

        if (errors.length > 0)
            return errors;

        return;
    },

    sync: function (method, model, options) {
        var formData = new FormData(),
                files = model.get("fileArray"),
                $progress = $('progress'),
                success = options.success,
                error = options.error;

        // Nothing other than create or update right now
        if (method !== "create" && method !== "update")
            return;

        // Build formData object
        formData.append("name", model.get("name"));
        formData.append("description", model.get("description"));
        formData.append("accesses", model.get("accesses"));
        formData.append("tags", model.get("tags"));
        formData.append("expirationDate", model.get("expirationDate"));
        formData.append("userId", model.get("userId"));
        formData.append("isNew", model.isNew());

        // if not new then capture id
        if (!model.isNew())
            formData.append('id', model.id);


        for (var i = 0; i < files.length; i++) {
            formData.append('file', files[i]);
        }

        xhr = new XMLHttpRequest();

        xhr.open('POST', '/genericHandlers/UploadDocsFile.ashx');


        xhr.onload = function () {
            if (xhr.status === 200) {
                if (success)
                    success();
            } else {
                if (error)
                    error();
            }
        }

        if ($progress.length > 0) {
            xhr.upload.onprogress = function (evt) {
                var complete;

                if (evt.lengthComputable) {
                    // Do the division but if you cant put 0
                    complete = (evt.loaded / evt.total * 100 | 0);
                    $progress[0].value = $progress[0].innerHTML = complete;
                }
            }
        }



        xhr.send(formData);
    },

    upload: function (changedAttrs, options) {
        this.save("create", changedAttrs, options);
    }

});
4

1 回答 1

1

document.location.href在尝试获取集合之前,您正在分配一个值:

document.location.href = fileRequest;
me.collection.fetch();

更改document.location.href将更改整个页面,并且在此过程中,任何当前正在运行的 JavaScript 都将被关闭,因此我不希望您me.collection.fetch()被执行。

于 2012-06-08T20:30:46.253 回答