使用sendAction()在Ember.js中实现数据向下动作模式

时间:2017-02-25 15:51:25

标签: javascript ember.js action

我正在做一个小应用程序来尝试学习Ember.js,但我真的很难实现数据向下动作组件。出于某种原因,我似乎无法发送'正确地备份到路由器的操作。我希望它会触发组件操作,但sendAction()似乎没有做任何事情。

我的代码如下:

我的组件(editable-cell.js):

import Ember from 'ember';

export default Ember.Component.extend({
  isEditing: false,
  startingText: "",
  saveAction: null,
  asdf: 'asdf jkl;',

  actions: {
    edit() {
      this.set('isEditing', true);
    },
    cancelEdit() {
      this.set('isEditing', false);
    },
    save() {
      console.log("SAVE");

      // I'm using the 'asdf' property just as a placeholder for now to get it working.
      this.sendAction('action', this.get('asdf'));
      this.set('isEditing', false);
    }
  }
});

我的组件模板(editable-cell.hbs):

<td>
  {{#if isEditing}}
    <form {{action 'saveAction' "Test Text" on='submit'}} class="form-inline">
      <div class="input-group">
        <input class="form-control" value="{{startingText}}">
        <div class="input-group-btn">
          <button type="submit" class="btn btn-success" {{action 'save'}}>Save</button>
          <button class="btn btn-danger" {{action 'cancelEdit'}}>Cancel</button>
        </div>
      </div>
    </form>

  {{else}}
    <span {{action 'edit'}}>{{startingText}}</span>
  {{/if}}
</td>

我的模板(books.hbs):

<h1>Books</h1>

<table class="table table-bordered table-striped">
  <thead>
  <tr>
    <th>
      Title
      <br><small class="small not-bold">(Click on name for editing)</small>
    </th>
    <th class="vtop">Author</th>
    <th class="vtop">Release Year</th>
    <th class="vtop">Library</th>
  </tr>
  </thead>
  <tbody>
  {{#each model as |book|}}
    <tr>
      <td>
        {{editable-cell startingText=book.title action=saveBook}}
      </td>
      <td>{{book.author.name}}</td>
      <td>{{book.releaseYear}}</td>
      <td>{{book.library.name}}</td>
    </tr>
  {{/each}}
  </tbody>
</table>

路由器(books.js):

import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return this.store.findAll('book');
  },
  actions: {
    saveBook: function(book) {
      console.log("In the book controller");
      console.log(book);
      book.save();
    }
  }
});

Controller(books.js):

import Ember from 'ember';

export default Ember.Controller.extend({
});

1 个答案:

答案 0 :(得分:2)

您正在使用经典操作,因此操作名称应作为字符串传递。所以这将解决问题{{editable-cell startingText=book.title action='saveBook'}}

使用minimum sample

创建了旋转

请查看ember component send action to route回答