提交输入时运行函数

Run function when input is submitted

本文关键字:函数 运行 输入 提交      更新时间:2023-09-26

我想要一个简单的输入&通过函数运行它的值,并在同一模板的另一个位置显示该函数的结果。我只是不知道在哪里连接绑定以显示函数的结果。我正在尝试对输入的值进行计算,并将结果推送到{{suggestedGrams}}。我正在使用此模板的生成视图。

这是我得到的:

模板

<script type="text/x-handlebars" data-template-name="brew">
{{input type="text" id="start-brew" placeholder="Enter a number, e.g: 16" name=id value=submittedOunces action="startBrew"}}
<p>We recommend using {{suggestedGrams}} grams of coffee for {{ounces}} oz. in a {{id}}.</p>
</script>

控制器

App.BrewController = Ember.ObjectController.extend({
submittedOunces: "",
// updates the {{ounces}} binding with value typed in input
ounces: function() {
     if (this.submittedOunces.length < 1) {
        return "";
     } else {
        return this.get("submittedOunces");
     }
}.property("submittedOunces"),
    actions: {
        startBrew: function () {
           // other logic is here to show hidden div's
        }
    }
});

我想我错过了一些显而易见的东西,但我对Ember完全陌生,所以很难找到合适的术语来找到我想要的东西。如有任何帮助,我们将不胜感激。

我通过添加另一个函数修复了这个问题,这要归功于@claptimes(请参阅对原始问题的评论)。我遇到的障碍是函数范围——我在一个函数中读取一个变量,出于某种原因,我希望它在另一个函数上可用。这是我的最后一个代码:

App.BrewController = Ember.ObjectController.extend({
    submittedOunces: "",
    ounces: function() {
         if (this.submittedOunces.length < 1) {
            return "";
         } else {
            return this.get("submittedOunces");
         }
    }.property("submittedOunces"),
    // This is where I was running into trouble.
    // I needed to declare the value again to gain access to it.
    grams: function() {
        var submittedOunces = this.get("submittedOunces");
        return submittedOunces * 2; // or whatever the function (in my case, a simple math formula) needs to be
    }.property("submittedOunces"),
    actions: {
        startBrew: function () {    
            $('.hide').fadeIn("fast");      
        }
    }
});