Ember.js:`<input />`字段的值何时保持为相应的`Controller`值?

时间:2013-04-29 12:33:09

标签: forms ember.js

更新:忘记提及我在版本1.0.0-rc2

中使用Ember

鉴于我有以下(非常简单)Ember.View对象:

App.AuthenticationLoginFormView = Ember.View.extend({
  tagName: 'form',
  classes: ['ajax-form']
}

Handlebars模板中使用,如下所示:

{{#view App.AuthenticationLoginFormView  }}
  <div class="ajax-form__row">
      <label>
          Account:<br/>
        {{ view Ember.TextField valueBinding="controller.account" }}
      </label>
  </div>
  <div class="ajax-form__row">
      <label>
          Username:<br/>
        {{ view Ember.TextField valueBinding="controller.username" }}
      </label>
  </div>
  <div class="ajax-form__row">
      <label>
          Password:<br/>
        {{ view Ember.TextField type="password" valueBinding="controller.password" }}
      </label>
  </div>
  <div class="ajax-form__row">
      <a href="" class="ajax-form__reset-link" {{action "reset" }} >Reset</a>
      <button class="ajax-form__button" {{action "login" target="controller"}} >Login</button>
  </div>
{{/view }}

Controller整个事情看起来像:

App.AuthenticationLoginController = Ember.Controller.extend({
  account: null,
  username: null,
  password: null,

  login: function() {
    // if I call, for example, this.get('account') I get the correct value
  }
});

正如我在代码示例中所写的那样,我在login函数中获得了'正确'值,该函数在表单提交时调用。但如果我尝试中断相应transitionTo对象中的Route操作,则控制器的所有值都显示为null

App.AuthenticationLoginRoute = Ember.Route.extend({
  events: {
    reset: function(){
      console.log(this.controller.get('account'); // <-- prints 'null'!
      this.transitionTo('reset');
    }
  }
}); 

即使控制器上没有执行input,也可以获取action字段的值吗?如果是的话,我该如何实施呢?在Ember.TextField

上触发的每个keyEvent是否需要听众?

1 个答案:

答案 0 :(得分:1)

不,你不需要在每个Ember.TextField上都有一个监听器,扩展它: 扩展Ember.TextField并挂钩到change事件:

App.MyTextField = Ember.TextField.extend({
    change: function() {
        console.log(this.get('value'));
    }
});

在你的模板中:

{{ view App.MyTextField type="password" valueBinding="controller.password" }}

现在每次在文本字段中键入内容时,都应该看到控制台输出。

希望它有所帮助。

编辑:

App.AuthenticationLoginRoute = Ember.Route.extend({
  events: {
    reset: function(){
      console.log(this.controllerFor('authenticationLogin').get('password')); // <-- what does this print?
      this.transitionTo('reset');
    }
  }
});