使用 jQuery.val() 更新 Ember TextField 的值

Update the value of Ember TextField using jQuery.val()

本文关键字:Ember TextField 的值 更新 jQuery val 使用      更新时间:2023-09-26

我有这些行:

 //this code is within a {{#each item in controller.content}} so id will not be unique
 //so by giving it just an id like i have is not going to work 
 {{#each item in controller.content}}
   <div class="pull-right" id="qnty-bulk">{{view Ember.TextField class="span1 qnty-bulk" id="qnty-bulk" valueBinding="item.qnty" type="number" min="1" max="9999999" disabled=true}}</div>
   <button class="pull-right" {{ action "increase" }}>
       Up
   </button>
 {{/each}}

在我的控制器中,我在操作中

 actions: {
    increase: function() {
        var inputField = $("#qnty-bulk");  //how can I access the Ember.TextField here for each of my items in the {{#each item in controller.content}}??
        var inputValue = inputField.val();
        inputValue = (inputValue != null && inputValue != '' ? (isNaN(inputValue) ? 0 : inputValue) : 0);
        inputValue++;
        console.log(inputField.val());
        inputField.val(inputValue);
    },

我想每次单击向上按钮时将文本字段的值增加 1我该怎么做?我可以使用jquery吗?

你可以

使用jQuery。但我认为您缺少数据绑定的概念。

您使用 item.qnty 属性为TextField进行了值绑定。

您的 increase 函数如下所示:

actions: {
    increase: function() {
        var quantity = this.get('model.item.qnty');
        this.set('model.item.qnty', quantity++);
    },
}

您甚至可以使用快捷功能:

actions: {
    increase: function() {
        this.increaseProperty('model.item.qnty');
    },
}

Ember 将自动检测item.qnty已更改并更新文本字段中的值。

切勿使用 Ember 框架以外的任何其他方式更新 Ember 值。这样做可能会导致您的 Ember 应用程序中断,或者在这种情况下无法按预期工作。

根据您的评论进行编辑。

您当前的 HBS:

{{#each item in controller}}
    <div {{action increase}} ></div>
{{/each}}

这将触发数组控制器中的increase函数,当您想要编辑数组中的项目时。

让我们为您的项目指定一个项目控制器:

{{#each item in controller itemController='myItem'}}
    <div {{action increase}} ></div>
{{/each}}

您的 MyItemController:

App.MyItemController = Ember.ObjectController.extend({
    actions: {
        increase: function(){
            this.increaseProperty('model.qnty');
        }
    }
})

这将触发项目控制器中的increase函数,您可以在其中直接访问项目。为数组使用一个 ArrayController 并为该数组中的项目提供一个 ObjectController 总是好的。

你不应该使用 jQuery。

您可以做的是将内容中的单个项目传递给increase操作,并在操作中增加其值。

<div class="pull-right">
 {{input value=item.qnty type="number" min="1" max="9999999" disabled=true}}
</div>
<button class="pull-right" {{ action "increase" this}}>
 Up
</button>

在控制器中:

actions: {
increase: function(item) {
    var qnty = Ember.get(item,'qnty');
    Ember.set(item,'qnty',++qnty);
 }
}

一个示例 JSBIN,适用于您的用例。