randombits
randombits

Reputation: 48500

Ember.js: How to observe when a value in an input field changes

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?

Upvotes: 1

Views: 7418

Answers (2)

kakigoori
kakigoori

Reputation: 1228

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.com/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.

Upvotes: 1

Kingpin2k
Kingpin2k

Reputation: 47367

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.com/niyawido/3/edit

Good: ObjectController with a model

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

Good: Controller without a model

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

Upvotes: 3

Related Questions