ember.jsember-model

Ember: Setting model to undefined on empty strings


There is a form on the template and when submit is pressed, it hits an action in the controller. When a user types something and deletes it, the binded property will be an empty string instead of undefined. I used the below to solve this problem, but it looks too hackish and unpresentable. Is there something which replaces empty strings on model attributes to undefined? Trying to set it in the model class doesn't work too since I can't get computed properties to work on itself. i.e user: function(){ return undefined if ""}

Here is my controller which handles the form submit:

Controller:
  actions:{
    save: function(){
      if(this.get('user.name')===""){
        this.set('user.name',undefined);
      }
      if(this.get('user.phone')===""){
        this.set('user.phone',undefined);
      }
      if(this.get('user.email')===""){
        this.set('user.email',undefined);
      }
  }
  // Process data
}

Solution

  • You can override the get of an Ember object to return undefined if the value is an empty string.

    var Model = Em.Object.extend({
      get: function(path) {
        var value = this._super(path);
        return value || undefined;
      }
    });
    
    var model = Model.create({
      name: 'Blessan',
      address: ''
    });
    
    alert(model.get('name'));
    alert(model.get('address'));
    

    Here is a working demo.