通过 ember 中的操作将非绑定输入值传递给 arraycontroller

Pass a non-bound input value to arraycontroller via an action in ember

我正在渲染一个迭代模板,其中包含一个输入字段和一个对我的数组控制器的操作,我可以愉快地传递当前模型,但我不知道如何传递未绑定的输入值内容。

举一个完全简单的例子,想象一下电子商务网站上的产品模板列表,其中包含一个数量字段和更新按钮。

{{#each product in controller}}
   {{product.name}}
   <input name="qty" placeholder="Qty" />
   <button {{action addToCart product}} ></button>  
{{/each}}

这是一个简单的产品列表,而不是查看购物车内容列表,因此数量字段与产品模型的一部分无关。我需要数量保持未绑定(始终加载空白)

如何将 qty 字段的值传递给 addToCart 操作?

您认为数量不应绑定到模型是正确的,但它应该绑定到 controller/component。

我建议提取一个组件并执行如下操作:

{{#each product in controller}}
   {{product-component product=product}}
{{/each}}

app/components/product-component.js中:

import Ember from 'ember';

export default Ember.Component.extend({
    quantity:0,
    actions: {
        addToCart: function (product, qty) {
            console.log(product.get('name') + ' ' + qty);
        }
    }
});

app/templates/components/product-component.hbs中:

   {{product.name}}
   {{input value=quantity name="qty" placeholder="Qty"}}
   <button {{action addToCart product quantity}} ></button>  

请注意,我们已将模型作为 product 传递,但我们绑定到 quantity,这不是 product 的 属性。