3
votes

I'm new in sencha touch and javascipt and i'm trying to init a value in function of others values in my sencha touch model. In java, I do this :

private int a,b,c;

public className(int a, int b){
    this.a = a;
    this.b = b;
    this.c = b - a;
}

In sencha i've tried to do that but i've an "Uncaught TypeError: Cannot call method 'hasOwnProperty' of undefined". Here is my model :

Ext.define('MyApp.className', {
extend: 'Ext.data.Model',

config: {

    fields: [
        { name: 'a', type: 'int' },
        { name: 'b', type: 'int' },
        { name: 'c', type: 'int'},
    ]

},

constructor: function(config) {

  var a = this.get('a');
  var b = this.get('b');
  this.set('c', b - a);

},

});

And here how I create my instance :

var instance = Ext.create('MyApp.className', {
    a : '5',
    b : '4'
});

I've tried to replace my method name from contructor to init, and now it works. But I don't know if it's the right way to do that, because the init function is not the constructor... What's the difference ? How write a constructor ?

Thanks per advance !

2

2 Answers

4
votes

you can actually extend the constructor but the arguments for constructor function is different, ans also you were not calling the parent class' constructor which is very important, try with below code

Ext.define('MyApp.className', {
   extend: 'Ext.data.Model',

   config: {
       fields: [
           { name: 'a', type: 'int' },
           { name: 'b', type: 'int' },
           { name: 'c', type: 'int'},
       ]  
   },

   constructor: function(data, id, raw, convertedData) {   // number of arguments is different
      // call parent first then you can do further processing
      this.callParent();

      var a = this.get('a');
      var b = this.get('b');
      this.set('c', b - a);
   },
});
2
votes

While @Saket Patel's answer is true, it is the wrong way to go about it in most cases. You should instead use the convert property available on any field, which gets passed both the value of field and an instance of the record:

Ext.define('MyModel', {
    extend: 'Ext.data.Model',

    config: {
        {
            name: 'a', type: 'int'
        },
        {
            name: 'b', type: 'int'
        },
        {
            name: 'c', type: 'int',
            convert: function(value, record) {
                return record.get('a') + record.get('b');
            }
        }
    }
});

var record = Ext.create('MyModel', {
    a: 1,
    b: 2
});

console.log(record.get('c')); // 3

More information here: http://docs.sencha.com/touch/2-0/#!/api/Ext.data.Field-cfg-convert