我有一个包含4个Model类的rails应用程序,每个表中都有多个实例。我已经在CoffeeScript中创建了backbone Model和Collection类来匹配。我可以成功地加载所有的集合,并且可以在视图中呈现它们。到现在为止还好。以下是我的一个集合,以及它的相关模型:
class window.CoffeeWater.Collections.Histories extends Backbone.Collection
url: '/api/histories'
model: History
class window.CoffeeWater.Models.History extends Backbone.Model
我需要能够创建一个History模型对象,然后将其添加到History集合中。文档指出,我必须在创建新模型时设置一个' collection‘属性,以便它从集合中获取'url’属性。我的问题是,我似乎不能正确地设置'collection‘属性值,因为没有在模型实例上设置url属性
attributes = {'start_time': new Date (1434740259016), 'stop_time': new Date (1434740259016 +(86400*1000)), 'valve_id': 2}
options = { collection: window.CoffeeWater.Collections.Histories }
history = new window.CoffeeWater.Models.History(attributes, options)
window.CoffeeWater.Objects.Collections.Histories.add(history)
检查得到的'history‘对象不会显示集合中已存在的模型中存在的相同属性,并且缺少url属性。
我现在有点不知所措。有没有人有这样做的例子?backbone.js文档没有显示任何相关的示例。
发布于 2015-06-19 22:43:55
模型中的url是这样定义的。
如果模型中有url属性。
class window.CoffeeWater.Models.History extends Backbone.Model
url:'/api/history/1'
然后,当使用model.fetch()时,它将调用该url。如果未找到此属性,它将查看关联的集合是否具有'url‘。您尝试设置此集合变量。
你遗漏的是这个。这
class window.CoffeeWater.Collections.Histories extends Backbone.Collection
实际上是一个类的定义。它还不是一个对象。您需要初始化它,就像在java中所做的那样。所以
var historyCollection=new window.CoffeeWater.Collections.Histories()
现在您有了一个集合对象。当你这样做的时候
historyCollection.add(history);
模型的“集合”被自动设置为"historyCollection“对象,其中包含一个”url“。因此,实际上,您不需要手动将其放入选项中。
基本上
attributes = {'start_time': new Date (1434740259016), 'stop_time': new Date (1434740259016 +(86400*1000)), 'valve_id': 2}
var historyCollection=new window.CoffeeWater.Collections.Histories()
var history = new window.CoffeeWater.Models.History(attributes)
historyCollection.add(history)
https://stackoverflow.com/questions/30945916
复制