How do I create a constructor in a sencha touch model?

I am new to sencha touch and javascipt and I am trying to output a value in a function of other 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 tried to do this but I have "Uncaught TypeError: Cannot call hasOwnProperty method 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 this is how I create my instance:

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

      

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

Thanks for the advance!

+3


source to share


2 answers


While @Saket Patel's answer is correct, in most cases this is not the correct way. Instead, you should use a property convert

available on any field that receives both the field value and the record instance:

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 info here: http://docs.sencha.com/touch/2-0/#!/api/Ext.data.Field-cfg-convert

+2


source


you can actually extend the constructor, but the arguments for the constructor function are different and you also didn't call 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);
   },
});

      

+4


source







All Articles