草庐IT

php - Backbone.js model.destroy() 不发送删除请求

coder 2023-06-15 原文

几天来我一直在努力让这个工作正常,但我只是想不通为什么当我想销毁一个属于集合的模型时(它正确地具有用于开始获取模型数据的 url 属性), 仅触发销毁“事件”,该事件冒泡到集合中,以便通过我的 ListView 轻松绑定(bind)。但它根本不会向服务器发送实际的 DELETE 请求或任何请求。我到处看,我看到每个人都使用集合的 url attr,或者如果模型没有连接到集合,则使用 urlRoot。我什至在实际的 this.model.destroy() 之前进行了测试以检查模型 < console.log(this.model.url());="">

我没有覆盖 backbone 的 destroy 和 sync 方法。此外,每个模型都有一个 id 属性,该属性是通过集合的提取(从数据库记录)填充的。

销毁发生在列表项 View 中,集合的“销毁”事件绑定(bind)在 ListView 中。所有这些都运行良好(事件处理),但问题是没有对服务器的请求。

我希望 backbone.js 会自动完成。这就是文档以及随处可见的大量示例所暗示的内容。

非常感谢任何可以提供有用输入的人。

仅供引用:我正在 wampserver PHP 5.3.4 上进行开发。

ListItemView = BaseView.extend({

    tagName: "li",

    className: "shipment",

    initialize: function (options) {
        _.bindAll(this);
        this.template = listItemTemplate;   
        this.templateEmpty = listItemTemplateEmpty;
    },  

    events: {
        'click .itemTag' : 'toggleData',
        'click select option' : 'chkShipper',
        'click .update' : 'update',
        'click button.delete' : 'removeItem'
    },  

    // ....

    removeItem: function() {
        debug.log('remove model');

        var id = this.model.id;

        debug.log(this.model.url());

        var options = {
            success: function(model, response) {
                debug.log('remove success');
                //debug.log(model);
                debug.log(response);
                // this.unbind();
                // this.remove();
            },
            error: function(model, response) {
                debug.log('remove error');
                debug.log(response);
            }
        };

        this.model.destroy(options);


        //model.trigger('destroy', this.model, this.model.collection, options);


    }

});


Collection = Backbone.Collection.extend({

    model: Model,

    url: '?dispatch=get&src=shipments',
    url_put : '?dispatch=set&src=shipments',

    name: 'Shipments',  

    initialize: function () {
        _.bindAll(this);
        this.deferred = new $.Deferred();
        /*
        this.fetch({
            success: this.fetchSuccess,
            error: this.fetchError
        });
        */
    },

    fetchSuccess: function (collection, response) {
        collection.deferred.resolve();
        debug.log(response);
    },

    fetchError: function (collection, response) {
        collection.deferred.reject();
        debug.log(response);
        throw new Error(this.name + " fetch failed");
    },

    save: function() {
        var that = this;
        var proxy = _.extend( new Backbone.Model(),
        {
            url: this.url_put,
            toJSON: function() {
                return that.toJSON();
            }
        });
        var newJSON = proxy.toJSON()
        proxy.save(
            newJSON,
            {
                success: that.saveSuccess,
                error: that.saveError
            }
        );
    },

    saveSuccess: function(model, response) {
        debug.log('Save successful');
    },

    saveError: function(model, response) {
        var responseText = response.responseText;
        throw new Error(this.name + " save failed");
    },

    updateModels: function(newData) {
        //this.reset(newData);
    }

});



ListView = BaseView.extend({

    tagName: "ul",

    className: "shipments adminList",

    _viewPointers: {},

    initialize: function() {
        _.bindAll(this);
        var that = this;
        this.collection;
        this.collection = new collections.ShipmentModel();
        this.collection.bind("add", this.addOne);

        this.collection.fetch({
            success: this.collection.fetchSuccess,
            error: this.collection.fetchError
        });


        this.collection.bind("change", this.save);
        this.collection.bind("add", this.addOne);
        //this.collection.bind("remove", this.removeModel);
        this.collection.bind("destroy", this.removeModel);
        this.collection.bind("reset", this.render);
        this.collection.deferred.done(function() {
            //that.render();
            that.options.container.removeClass('hide');
        });             

        debug.log('view pointers');

        // debug.log(this._viewPointers['c31']);
        // debug.log(this._viewPointers[0]);

    },

    events: {

    },

    save: function() {
        debug.log('shipments changed');
        //this.collection.save();
        var that = this;
        var proxy = _.extend( new Backbone.Model(),
        {
            url: that.collection.url_put,
            toJSON: function() {
                return that.collection.toJSON();
            }
        });
        var newJSON = proxy.toJSON()
        proxy.save(
            newJSON,
            {
                success: that.saveSuccess,
                error: that.saveError
            }
        );
    },

    saveSuccess: function(model, response) {
        debug.log('Save successful');
    },

    saveError: function(model, response) {
        var responseText = response.responseText;
        throw new Error(this.name + " save failed");
    },

    addOne: function(model) {
        debug.log('added one');
        this.renderItem(model);
        /*
        var view = new SB.Views.TicketSummary({
            model: model
        });
        this._viewPointers[model.cid] = view;
        */
    },

    removeModel: function(model, response) {
        // debug.log(model);
        // debug.log('shipment removed from collection');

        // remove from server
        debug.info('Removing view for ' + model.cid);
        debug.info(this._viewPointers[model.cid]);
        // this._viewPointers[model.cid].unbind();
        // this._viewPointers[model.cid].remove();
        debug.info('item removed');
        //this.render();
    },

    add: function() {
        var nullModel = new this.collection.model({
            "poNum" : null,
            "shipper" : null,
            "proNum" : null,
            "link" : null
        });
        // var tmpl = emptyItemTmpl;
        // debug.log(tmpl);
        // this.$el.prepend(tmpl);
        this.collection.unshift(nullModel);
        this.renderInputItem(nullModel);                
    },

    render: function () {
        this.$el.html('');
        debug.log('list view render');
        var i, len = this.collection.length;
        for (i=0; i < len; i++) {
            this.renderItem(this.collection.models[i]);
        };
        $(this.container).find(this.className).remove();

        this.$el.prependTo(this.options.container);

        return this;
    },          

    renderItem: function (model) {
        var item = new listItemView({
            "model": model
        });

        // item.bind('removeItem', this.removeModel);

        // this._viewPointers[model.cid] = item;
        this._viewPointers[model.cid] = item;
        debug.log(this._viewPointers[model.cid]);
        item.render().$el.appendTo(this.$el);
    },

    renderInputItem: function(model) {
        var item = new listItemView({
            "model": model
        });
        item.renderEmpty().$el.prependTo(this.$el);
    }

});

P.S...同样,这里有从其他地方引用的代码。但请注意:该集合确实有一个 url 属性集。它确实适用于初始获取以及为保存对模型所做的更改而触发的更改事件。但是列表项 View 中的 destroy 事件虽然成功触发了“destroy”事件,但它没有发送“DELETE”HTTP 请求。

最佳答案

Do your models have an ID? If not, the HTTP request won't be sent. – nikoshr May 14 at 18:03

非常感谢! Nikoshr 的小评论正是我所需要的。我花了最后 5 个小时来解决这个问题。我只需在模型中的默认值中添加一个 id。

关于php - Backbone.js model.destroy() 不发送删除请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10587897/

有关php - Backbone.js model.destroy() 不发送删除请求的更多相关文章

  1. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  2. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  3. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  4. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  5. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  6. ruby - 如何安全地删除文件? - 2

    在Ruby中是否有Gem或安全删除文件的方法?我想避免系统上可能不存在的外部程序。“安全删除”指的是覆盖文件内容。 最佳答案 如果您使用的是*nix,一个很好的方法是使用exec/open3/open4调用shred:`shred-fxuz#{filename}`http://www.gnu.org/s/coreutils/manual/html_node/shred-invocation.html检查这个类似的帖子:Writingafileshredderinpythonorruby?

  7. ruby - 使用 Ruby 通过 Outlook 发送消息的最简单方法是什么? - 2

    我的工作要求我为某些测试自动生成电子邮件。我一直在四处寻找,但未能找到可以快速实现的合理解决方案。它需要在outlook而不是其他邮件服务器中,因为我们有一些奇怪的身份验证规则,我们需要保存草稿而不是仅仅发送邮件的选项。显然win32ole可以做到这一点,但我找不到任何相当简单的例子。 最佳答案 假设存储了Outlook凭据并且您设置为自动登录到Outlook,WIN32OLE可以很好地完成此操作:require'win32ole'outlook=WIN32OLE.new('Outlook.Application')message=

  8. ruby-on-rails - 标准化文件名的字符串,删除重音和特殊字符 - 2

    我正在尝试找到一种方法来规范化字符串以将其作为文件名传递。到目前为止我有这个:my_string.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/n,'').downcase.gsub(/[^a-z]/,'_')但第一个问题:-字符。我猜这个方法还有更多问题。我不控制名称,名称字符串可以有重音符、空格和特殊字符。我想删除所有这些,用相应的字母('é'=>'e')替换重音符号,并将其余的替换为'_'字符。名字是这样的:“Prélèvements-常规”“健康证”...我希望它们像一个没有空格/特殊字符的文件名:“prelevements_routin

  9. ruby-on-rails - ActiveRecord destroy_all - 2

    在Rails4.1中,ActiveRecorddestroy_all是否将整个函数包装在一个事务中?例如,如果我有一堆记录,我对其执行了destroy_all操作,它们对这些单独的对象运行了一些回调,其中一个失败了,整个操作会在那个时候回滚吗? 最佳答案 看起来不像:#Fileactiverecord/lib/active_record/relation.rb,line386defdestroy_all(conditions=nil)ifconditionswhere(conditions).destroy_allelseto_a.

  10. ruby-on-rails - 为什么在 Rails 5.1.1 中删除了 session 存储初始化程序 - 2

    我去了这个website查看Rails5.0.0和Rails5.1.1之间的区别为什么5.1.1不再包含:config/initializers/session_store.rb?谢谢 最佳答案 这是删除它的提交:Setupdefaultsessionstoreinternally,nolongerthroughanapplicationinitializer总而言之,新应用没有该初始化器,session存储默认设置为cookie存储。即与在该初始值设定项的生成版本中指定的值相同。 关于

随机推荐