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

时间:2013-11-11 08:12:45

标签: javascript jquery ember.js

我认为这些行:

 //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吗?

2 个答案:

答案 0 :(得分:1)

你可以使用jQuery。但我认为你错过了数据绑定的概念。

您使用TextField属性为item.qnty创建了值绑定。

你的增加函数看起来像这样:

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已更改并更新TextField中的值。

除非使用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总是好的。

答案 1 :(得分:0)

你不应该使用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,用于您的用例。