Sproutcore 2.0一对多的关系

时间:2011-11-02 23:20:26

标签: sproutcore sproutcore-2

我一直在努力使用Sproutcore 2.0来解决一对多关系中的绑定问题。

我的模板看起来像这样:

<script type="text/x-handlebars">
  {{#collection contentBinding="HTH.projectsController.content"}}
    <h3>{{content.title}}</h3>
    {{#collection contentBinding="content.tasks"}}
    <span>{{content.title}}</span>
    {{/collection}}
  {{/collection}}
</script>

虽然实际代码如下:

HTH.Project = SC.Record.extend({
  title: SC.Record.attr(String),
  tasks: SC.Record.toMany('HTH.Task',{
    isMaster: YES,
    inverse: 'project'
  })
});

HTH.Task = SC.Record.extend({
  title: SC.Record.attr(String),
  project: SC.Record.toOne('HTH.Project', {
    isMaster: NO
  })
});

HTH.Project.FIXTURES = [ { guid: 1, title: 'Send man to moon', tasks: [1,2]}, 
                         { guid: 2, title: 'Master handstand', tasks: [3]}];
HTH.Task.FIXTURES    = [ { guid: 1, title: 'Find rocket',    project: 1}, 
                         { guid: 2, title: 'Find fuel',      project: 1},
                         { guid: 3, title: 'Stand on hands', project: 2}];

HTH.store = SC.Store.create().from(SC.Record.fixtures);

// Controllers

HTH.projectsController = SC.ArrayProxy.create({
  content: HTH.store.find(HTH.Project)
});

现在我可以更新任务,这些将更新UI。例如:

HTH.store.find(HTH.Project).get('firstObject').set('title','Updated the title!');

但是,如果我创建一个新项目并动态添加任务,UI将添加新项目,但从不添加任何优惠:

var project = HTH.store.createRecord(HTH.Project, {title: "New" });
var task = HTH.store.createRecord(HTH.Task, {title: "New task" });
project.get('tasks').pushObject(task);

我确信这取决于没有按预期工作的绑定,或者需要遵守的属性。有人可以帮忙吗?

注意:在SproutCore 2.0成为Ember.js之前,已经提出了这个问题。它还引用了SproutCore 1.x数据存储的非官方端口,该端口已被官方支持的ember-data库取代。

1 个答案:

答案 0 :(得分:1)

为了使记录可用,它必须是assigned an ID

这意味着:

var project = HTH.store.createRecord(HTH.Project, {title: "New" });
var task = HTH.store.createRecord(HTH.Task, {title: "New task" });
project.get('tasks').pushObject(task);

变为:

var project = HTH.store.createRecord(HTH.Project, {title: "New" }, 123);
var task = HTH.store.createRecord(HTH.Task, {title: "New task" }, 321);
project.get('tasks').pushObject(task);

然后,更改将反映在用户界面