Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js Dynamic Model Properties

Ember.js (and Ember Data) allows me to specify properties of a model, such as id, label and description. But I allow my users to add their own properties to any model, which are obviously impossible for me to know about. Is there any way I can dynamically add properties to a model at runtime? (And more importantly, will Ember.js recognize changes on those properties and save them?)

like image 935
GJK Avatar asked Jul 11 '13 13:07

GJK


1 Answers

Ember defines object properties via Ember.defineProperty. The signature is Ember.defineProperty(object, propertyName, function). For instance to define a lorem property backed by _lorem, you can use

Ember.defineProperty(this, 'lorem', 
  Ember.computed(function (key, value) {
    if (value) {
      this.set('_lorem', value);
      return value;
    } else {
      return this.get('_lorem');
    }
  }  
));

You can call this method based in a user input handler when the propertyName is dynamic. This sort of thing is best suited for extending the Meta object system. Caution is advised, especially with user input!

like image 66
Darshan Sawardekar Avatar answered Oct 16 '22 15:10

Darshan Sawardekar