簡體   English   中英

在ember.js中編輯模型

[英]Editing models in ember.js

我試圖把我的頭纏在ember.js上。 我正在寫一個小的Web應用程序,顯示某些咖啡豆的價格。 用戶可以添加新的咖啡豆,但是現在我想讓用戶能夠編輯現有的咖啡豆。 如果用戶雙擊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小提琴的鏈接: http : //jsfiddle.net/cspears2002/y8MT3/

雙擊名稱或價格確實可以使我進入editCoffee函數,但是由於某些原因,我無法編輯咖啡豆。 有任何想法嗎?

有幾個問題。 isEditing的靠外的actions亂碼, isEditing並沒有真正的存在ArrayController因為屬性是相關的單個項目,而不是整個數組。 話雖這么說,項目控制器將是在此處使用的適當方法。 在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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM