简体   繁体   English

骨干模型保存问题

[英]backbone model save issue

I just started working on backbone a week ago, please don't mind if this question is silly. 我刚刚在一周前开始研究骨干,请不要介意这个问题是否愚蠢。 Alright, here's what I am trying to do. 好吧,这就是我想要做的。

I have a model called Item and a collection called Items. 我有一个名为Item的模型和一个名为Items的集合。 There are two views, one to add the item and the other to list the items. 有两个视图,一个用于添加项目,另一个用于列出项目。 The issue I am having is when I am trying to save the item, it gets saved correctly for the first time. 我遇到的问题是当我尝试保存项目时,它第一次正确保存。 The next time when I add a new item, the item is created successfully, but the previous item added also gets updated with the attributes of the new item. 下次添加新项目时,该项目已成功创建,但添加的上一项目也会使用新项目的属性进行更新。 This happens to all the successive items being added. 这种情况发生在所有连续的项目中。

I am guessing that all my models in the collection are being updated OR I need to have my own save method. 我猜测集合中的所有模型都在更新,或者我需要拥有自己的保存方法。 I actually am not able to figure out what I am doing wrong. 我实际上无法弄清楚我做错了什么。 I just want to save the model in question with the view, not all the models in the collection. 我只想用视图保存有问题的模型,而不是集合中的所有模型。 Would really appreciate some pointers. 真的很感激一些指针。

Link to the demo . 链接到演示

Item add/edit view 项目添加/编辑视图

define([
  'jquery',
  'use!underscore',
  'use!backbone',
  'mustache',
  'models/item',
  'views/bootstrap',
  'text!templates/items/edit.mustache',
  'text!templates/items/new.mustache',
  'handlebars',
  'bootstrap'

], function($, _, Backbone, Mustache, Item, Bootstrap, editTemplate, newTemplate, Handlebars){

  var app = new Backbone.Router

  var ItemEditView = Backbone.View.extend({

    el: $('#page'),

    events: {
      'submit #new-item': 'saveItem',
      'click .cancel': 'cancelItem'
    },

    initialize: function(options){
      if (!this.model.isNew()) {
        this.model.bind('change', this.render, this)
        this.model.fetch()
      }
    },

    render: function(){
      var item = this.model.attributes
      var template = this.model.isNew() ? newTemplate : editTemplate
      var compiledTemplate = Mustache.render(template, item )
      $(this.el).html(compiledTemplate)
      if (this.model.isNew()) $('#itemName').focus()
      return this
    },


    /*
     *  Event actions
     */

    saveItem: function(e) {
      e.preventDefault()

      var item = {
        name: $('#itemName').val(),
        price: $('#itemPrice').val()
      }
      var self = this
      this.model.save(item, {
        success: function (model, response) {
          app.navigate('items/'+model.id, {trigger: true, replace: true})
        },
        error: function (model, response) {
          new Bootstrap.alert({ el: $('#page') }).render(response, 'error')
        }
      })
    },

    cancelItem: function (e) {
      if (this.model.isNew())
        app.navigate('items', {trigger: true, replace: true})
      else
        app.navigate('items/'+this.model.id, {trigger: true, replace: true})
    }

  })

  return ItemEditView
})

Item model 物品模型

define([
  'use!underscore',
  'use!backbone'
], function(_, Backbone) {
  var Item = Backbone.Model.extend({

    urlRoot: 'api/items',

    idAttribute: '_id'

  });

  return Item;
});

Items collection 物品收藏

define([
  'jquery',
  'use!underscore',
  'use!backbone',
  'models/item'
], function($, _, Backbone, Item){
  var Items = Backbone.Collection.extend({

    model: Item,

    url: 'api/items/'

  });

  return Items;
});

Link to the Source code (in case) 链接到源代码 (以防万一)

When you are done using your form, either the form is submitted or canceled you must either destroy or the view by calling ItemView.remove() or at least un-delegate events:: 当您使用表单时,无论是提交还是取消表单,您都必须通过调用ItemView.remove()或至少取消委托事件来销毁或查看视图::

saveItem: function(e) {
  e.preventDefault()

  var item = {
    name: $('#itemName').val(),
    price: $('#itemPrice').val()
  }
  var self = this
  this.model.save(item, {
    success: function (model, response) {
      app.navigate('items/'+model.id, {trigger: true, replace: true})
    },
    error: function (model, response) {
      new Bootstrap.alert({ el: $('#page') }).render(response, 'error')
    }
  })
  this.remove(); // undelegate events for later views.
},

cancelItem: function (e) {
  if (this.model.isNew())
    app.navigate('items', {trigger: true, replace: true})
  else
    app.navigate('items/'+this.model.id, {trigger: true, replace: true});
  this.remove(); // undelegate events for later views.
} 

As the events are delegated to #page and your old views exist after creating new ones their save and cancel methods will still trigger until they are removed. 由于事件被委托给#page,并且在创建新视图后存在旧视图,因此保存和取消方法仍将触发,直到它们被删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM