Emberjs:如何在模型创建后刷新父模板

时间:2014-03-13 21:45:39

标签: ember.js

我正在构建一个包含以下代码的应用:

路线:

App.Router.map(function() {
  this.resource('gradebooks', function() {
    this.resource('gradebook', { path: ':gradebook_id' });
  });
});

App.IndexRoute = Em.Route.extend({
  redirect: function() {
    this.transitionTo('gradebooks');
  }
})

App.GradebooksRoute = Em.Route.extend({
  setupController: function(controller, model) {
    Em.$.getJSON('/data/gradebooks/get', function(data) {
      controller.set('model', data);
    });
  }
});

App.GradebookRoute = Em.Route.extend({
  model: function(params) {
    var id = params.gradebook_id;
    return Em.$.getJSON('/data/gradebooks/get/' + id);
  }
})

控制器:

App.GradebooksController = Em.ArrayController.extend({
  isActive: false,
  actions: {
    createGradebook: function(newTitle) {
      var self = this;
      if(newTitle.trim()) {
        Em.$.get('/data/gradebooks/add/' + newTitle, {}, function(json) {
          Em.$('#create-gradebook-modal').modal('hide').find('input').val('');
          self.transitionToRoute('gradebook', json.id);
        }, 'json');
      }
    }
  }
});

模板(gradebooks.hbs):

<div class="sidebar">
  <div class="btn-container">
    <button class="btn btn-block btn-info" data-toggle="modal" data-target="#create-gradebook-modal">
      <i class="fa fa-book"></i>
      Create Gradebook
    </button>
  </div>

  <ul>
    {{#each}}

    <li {{bind-attr class="isActive:active"}}>
      {{#link-to "gradebook" _id}}
        {{title}}
      {{/link-to}}
    </li>

    {{/each}}
  </ul>
</div>

<div class="content">
  <div class="container-fluid">
    {{outlet}}
  </div>
</div>

模板(gradebook.hbs):

<h1>{{title}} <small>{{_id}}</small></h1>

<div class="btn-container">
  <button class="btn btn-default"><i class="fa fa-pencil"></i> Rename</button>
  <button class="btn btn-danger"><i class="fa fa-trash-o"></i> Trash</button>
</div>

我遇到问题的是GradebooksController.actions.createGradebook,我发送了创建模型的请求,然后转换到我刚创建的成绩簿。创建和转换工作正常,但我希望侧栏(gradebooks.hbs)显示新创建的成绩簿。

我认为这与更新GradebooksRoute中的模型有关。如何在创建成绩簿后再次从服务器获取模型。

1 个答案:

答案 0 :(得分:3)

要详细说明@ fanta的评论,你会想要做这样的事情:

App.GradebooksController = Em.ArrayController.extend({
  isActive: false,
  actions: {
    createGradebook: function(newTitle) {
      var self = this;
      if(newTitle.trim()) {
        var gradebook = Em.$.getJSON('/data/gradebooks/add/' + newTitle, {}, function(json) {
          Em.$('#create-gradebook-modal').modal('hide').find('input').val('');
          self.transitionToRoute('gradebook', json.id);
        }, 'json');
        self.get('content').pushObject(gradebook);
      }
    }
  }
});