Backbone集合获取错误,没有任何信息

时间:2012-06-08 19:45:51

标签: ajax rest backbone.js

我正在处理我正在使用的骨干集合的奇怪问题。在我的代码的一个特定实例中,我执行了一次获取(确切地说我在代码的其他区域中如何工作,这一切都工作正常),fetch似乎永远不会进入服务器,开发人员工具将请求显示为红色状态/文本字段中的单词(已取消)。

我已经走进了主干同步方法,我看到正在构建$ .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);
    }

});

1 个答案:

答案 0 :(得分:1)

在尝试获取收藏集之前,您正在为document.location.href分配值:

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

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