Extra fields in model

188 Views Asked by At

im using Backbone.js to manage models and collections in my app. So, i have a "Usuario" model that match with a user entity in the database. This is the code:

var Usuario = Backbone.Model.extend({
   defaults:{
      idusuario: 'undefined',
      apellido: 'undefined',
      nombre: 'undefined',
      dni: 'undefined',
      dom_usuario: 'undefined',
      nombreusuario: 'undefined',
      activo: 'undefined',
      bloqueado: 'undefined',
      recomendar_cambio_clave: 'undefined',
      isChecked: false
   }
});

All fields of the model are in the entity user, except "isChecked".The isChecked attribute, will be true when the user model is checcked. But when i query by "isChecked" js not recognize the variable:

console.log(this.model.get('isChecked')); 
undefined
console.log(this.model.get('nombre')); 
Horacio José

Any ideas ?.

UPDATE 1 It is a extract of my code, where load the collection (of Usuario) via Ajax:

var anUrl = $("#ajax-call").val();
var myCol = new CustomCollection({
    model: Usuario,
    filterAttribute: 'apellido'
});

myCol.fetch({async: false, url: anUrl});
myCol.saveOriginal();
console.log(myCol);

When, show in console the collection, the models not contains "isChecked" property: enter image description here

2

There are 2 best solutions below

2
Meta On

With the details you've provided it's hard to know if the error is in your view's initialization or anything else. Using this fiddle you can see your example works perfectly. I created a view in that fiddle trying to mimic your scenario.

However, don't confuse 'undefined' or "undefined" with undefined. "undefined" == undefined and "undefined" === undefined are both false.

So, your model should be:

var Usuario = Backbone.Model.extend({
   defaults : {
      idusuario : undefined,
      apellido : undefined,
      nombre : undefined,
      dni : undefined,
      dom_usuario : undefined,
      nombreusuario : undefined,
      activo : undefined,
      bloqueado : undefined,
      recomendar_cambio_clave : undefined,
      isChecked : false
   }
});

And then:

var u = new Usuario();
console.log(u.get("isChecked"));

Should give your expected result.

0
ramiromd On

I solve mi problem. I create dynamically the property "isChecked", querying is the value is defined or not:

toggleModel: function(){
    var current = this.model.get('isChecked');
    var status =  current === undefined ? true : !current; 
    this.model.set('isChecked',status);
}

Thanks @Meta for the reply.