最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ember.js: How to observe when a value in an input field changes - Stack Overflow

programmeradmin2浏览0评论

I need to create a simple HTML input text field in my Ember.js app. The value to this particular input box is not bound to any specific model. When the input text box blurs or loses focus, I need to be able to run some JavaScript. In my template, I have this so far:

{{input valueBinding="pitcherSalary" placeholder=0}}

I tried observing the value of pitcherSalary by doing the following in the controller without any luck:

MyApp.OptimalController = Ember.ObjectController.extend({
 pitcherSalaryObserver: function () {
    var self = this;
    console.log("changing....");
  }.observes('pitcherSalary'), 
});

What's the correct way of doing this?

I need to create a simple HTML input text field in my Ember.js app. The value to this particular input box is not bound to any specific model. When the input text box blurs or loses focus, I need to be able to run some JavaScript. In my template, I have this so far:

{{input valueBinding="pitcherSalary" placeholder=0}}

I tried observing the value of pitcherSalary by doing the following in the controller without any luck:

MyApp.OptimalController = Ember.ObjectController.extend({
 pitcherSalaryObserver: function () {
    var self = this;
    console.log("changing....");
  }.observes('pitcherSalary'), 
});

What's the correct way of doing this?

Share Improve this question asked Jun 10, 2014 at 0:30 randombitsrandombits 48.6k79 gold badges273 silver badges449 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

You say it isn't backed by some model, yet your controller is saying it's backed by some model. It's likely you're confusing Ember, it wants to save to the model, which should be backing the controller, but it finds no model. ObjectController proxies properties to/from the controller to the model, and when it has no model, it yells about misuse.

Bad: ObjectController without a model

http://emberjs.jsbin./niyawido/3/edit

Good: ObjectController with a model

http://emberjs.jsbin./niyawido/4/edit

Good: Controller without a model

http://emberjs.jsbin./niyawido/2/edit

Why not use a plain old "value" in your input tag? Here's a fat example that uses the style of observable you want using the prototype extension: http://emberjs.jsbin./zuxuli/2/edit

My inputs:

{{input type=number value=amount placeholder="Billed Amount"}}
{{input type="checkbox" checked=roundTip}} //"checked" is a kind of value attrib

My observables:

observeStuff: function () {
  console.log("blah!!!");
}.observes('roundTip'),

observeStuff2: function () {
  console.log("crap!!!");
}.observes('amount'),

Hope this helps.

edit: see Ember.Observable and #addObserver for better documentation.

发布评论

评论列表(0)

  1. 暂无评论