Backbone.js保存模型的属性是其他模型的数组

Backbone.js saving model with attribute that is array of other models

本文关键字:模型 其他 数组 属性 js Backbone 保存      更新时间:2023-09-26

我正在写第一个开源的Backbone.js应用。存储库在这里https://github.com/defrag/Backbone-Invoices

我有保存LineItems的发票数组的问题。只在编辑后保存,因为它将行项从当前编辑的发票保存到本地存储中的所有发票。不知道为什么会这样,他们总是有相同的cid。创建发票时的默认行项始终为cid0。任何帮助吗?

class window.Invoice extends Backbone.Model
  initialize: ->
  defaults:
    date: new Date
    number: '000001'
    seller_info: null
    buyer_info: null  
    line_items: [new LineItem]

我不明白的最后一件事是为什么主干不保存嵌套的属性。正如你将在repo中看到的那样:

handleSubmit: (e) ->        
data = { 
  date : @$("input[name='date']").val(), 
  number : @$("input[name='number']").val(), 
  buyer_info : @$("textarea[name='buyer_info']").val(), 
  seller_info : @$("textarea[name='seller_info']").val(),
  line_items: @model.line_items.toJSON()
}    
if @model.isNew()
  invoices.create(data)
else
  @model.save(data)
e.preventDefault()
e.stopPropagation()    
$(@el).fadeOut 'fast', ->
  window.location.hash = "#"

事情是在编辑表单和更改行项的值之后,它们在集合中不会改变。添加新的发票行项目收集工作。任何帮助吗?:)我很难理解每件事是如何工作的:)

你可以在这里查看:http://backbone-invoices.brillante.pl/

默认值是文字值,在定义时求值。这意味着对于Invoice的每个实例,您都将LineItem的相同实例分配给数组。

解决这个问题很简单:使用函数返回数组。这样,每次创建发票时都会得到一个新的行项目数组:

window.Invoice = Backbone.Model.extend({
  defaults: {
    date: function(){ return new Date(); },
    line_items: function(){ return [new LineItem()]; },
    other: "stuff"
  }
});