【问题标题】:Editing models in ember.js在 ember.js 中编辑模型
【发布时间】:2014-02-02 14:10:38
【问题描述】:

我正试图围绕 ember.js。我正在编写一个显示某些咖啡豆价格的小型网络应用程序。用户可以添加新的咖啡豆,但现在我想让用户能够编辑现有的咖啡豆。如果用户双击 bean 的条目,那么他或她应该能够输入新名称或价格:

<script type="text/x-handlebars" data-template-name="coffee">
    <table>
      <tr>
        <th>Beans</th>
        <th>Prices</th>
      </tr>
      {{#each}}
      <tr>
        {{#if isEditing}}
          <td>{{input type="text"}}</td>
          <td>{{input type="text"}}</td>
          <td><button class="delete">Delete</button></td>
        {{else}}
          <td {{action "editCoffee" on="doubleClick"}}>{{bean}}</td>
          <td {{action "editCoffee" on="doubleClick"}}>{{price}}</td>
          <td><button class="delete">Delete</button></td>
        {{/if}}
      </tr>
      {{/each}}
    </table>

    {{input type="text" placeholder="Beans" value=newBean}}
    {{input type="text" placeholder="Price" value=newPrice}}
    <button type="button" {{action 'createCoffee'}}>Submit</button>

  </script>

这是控制器的代码:

// Controllers
App.CoffeeController = Ember.ArrayController.extend({
  actions: {
    createCoffee: function() {
      // Get the bean name
      var bean = this.get('newBean');
      if (!bean.trim()) { return; }

      // Get the price
      var price = this.get('newPrice');
      if (!price.trim()) { return; }

      // Create the new coffee model
      var coffee = this.store.createRecord('coffee', {
        bean: bean,
        price: price
      });

      // Clear the text fields
      this.set('newBean', '');
      this.set('newPrice', '');

      // Save the new model
      coffee.save();
    },

    isEditing: false,

    editCoffee: function () {
      console.log('Hello World');
      this.set('isEditing', true);
    }

  }
});

这里是 JS Fiddle 的链接:http://jsfiddle.net/cspears2002/y8MT3/

双击名称或价格确实可以让我进入 editCoffee 功能,但由于某些原因我无法编辑咖啡豆。有什么想法吗?

【问题讨论】:

    标签: javascript ember.js


    【解决方案1】:

    有几个问题。 isEditing 应该位于 actions 散列之外,而 isEditingArrayController 上并不真正存在,因为该属性与单个项目相关,而不是与整个数组相关。话虽这么说,项目控制器在这里使用是合适的。在 ember 中,您可以告诉数组控制器在迭代项目列表时应该使用一个项目控制器。最后一点,表格在 ember 中会导致大量问题,因为它会在页面中删除和插入 dom,并且根据浏览器的不同,这可能会导致表格出现大量问题。因此,为了向您展示如何修复它,我撕掉了所有桌子上的东西。

    App.CoffeeItemController = Em.ObjectController.extend({    
      isEditing: false,
    
      actions: {
        editCoffee: function () {
          this.toggleProperty('isEditing');
        }
      }
    });
    
    App.CoffeeController = Ember.ArrayController.extend({
      itemController: 'coffeeItem'
      ....
    

    http://jsfiddle.net/y8MT3/11/

    【讨论】:

    • 像魅力一样工作!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 2013-12-17
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    相关资源
    最近更新 更多