简体   繁体   中英

Emberjs: Two-Way Data-binding between Number Inputs

I am looking at data binding in Ember, and I want to bind two input type="number" elements so that changing either of the elements will update the other element. Here is the JSBin .

What I would like to have is the following:

Biker = DS.Model.extend(
    bikes: (->
        @get("tires") / 2
    ).property("tires")
    tires: (->
        @get("bikes") * 2
    ).property("bikes")
)

But that will result in the following stack overflow:

Uncaught RangeError: Maximum call stack size exceeded ember.js:1 Ember.assert ember.js:1 get ember.js:2167 Ember.Observable.Ember.Mixin.create.get ember.js:12425 (anonymous function) biker.js:32 ComputedPropertyPrototype.get ember.js:4951 get ember.js:2176 Ember.Observable.Ember.Mixin.create.get ember.js:12425 (anonymous function) biker.js:29 ComputedPropertyPrototype.get

What is the best way to achieve 2-way absolute data-binding with input elements?

Note: I asked something similar, but about angular .

Instead of writing circular code, have just one of the properties watch the other. Ember's computed properties allow you to define setter and getter functions for this exact purpose:

App.Biker = DS.Model.extend({
  bikes: DS.attr('number'),
  tires: function(key, value) {
    // Setter
    // Says: if we did this.set('tires', something);
    if (arguments.length > 1) {
      var bikes = value != 0 ? value / 2 : 0; // Incase zero bikes
      this.set('bikes',  bikes);
    }

    // Getter
    return this.get('bikes') * 2;
  }.property('bikes')
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM