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

Mic*_*hal 1 javascript coffeescript backbone.js

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

我在为Invoice保存LineItems数组时遇到问题.好吧,只有在编辑后保存,因为它将当前编辑的发票中的行项目保存到localstorage中的所有发票.Dunno为什么会这样,他们总是有相同的Cids.创建发票时的默认订单项始终为cid0.有帮助吗?

class window.Invoice extends Backbone.Model

  initialize: ->

  defaults:
    date: new Date
    number: '000001'
    seller_info: null
    buyer_info: null  
    line_items: [new LineItem]
Run Code Online (Sandbox Code Playgroud)

我不明白的最后一件事是为什么骨干不能保存嵌套属性.正如您将在回购中看到的那样:

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 = "#"
Run Code Online (Sandbox Code Playgroud)

事情是在编辑表单和更改行项目的值之后,它们不会在集合中更改.添加新的发票订单项集合工作.有帮助吗?:)我很难理解每个人的工作方式:)

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

Der*_*ley 8

默认值是文字值,在定义时计算.这意味着您要为每个Invoice实例为数组分配相同的LineItem实例.

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

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

  • 好答案.或者,在`initialize`方法中放入`@line_items = [new LineItem]`. (2认同)