【问题标题】:Pass a non-bound input value to arraycontroller via an action in ember通过 ember 中的操作将未绑定的输入值传递给 arraycontroller
【发布时间】:2015-02-12 16:12:28
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    你是正确的,数量不应该绑定到模型,但它应该绑定到控制器/组件。

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

    {{#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 的属性。

    【讨论】:

    • 传奇!组件就是答案。稍微超出了我的问题范围,但可能值得提供组件支持代码,以便为像我这样的组件提供完整的解决方案 pastebin.com/r3XfNWpX(我将 product-component 更改为 product-list 以避免 ProductComponentComponent)
    • 我更新了答案以包含组件定义,并假设用户正在使用 ember-cli。我看到您正在使用全局变量,但由于社区提倡使用 ember-cli 和 ES6 exports,我觉得这更有用。
    猜你喜欢
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多