Question

I have a problem while initializing a Backbone model with some data coming from Jackson.

The received data happens to have a listPropertyValue, which is originally a Java List of objects. When doing the initialize() method I make it a Backbone collection without much problem.

But the final SomeModel constructor also adds an attribute called listPropertyValue as a JavaScript array, which I don't want.

How may I discard or reject this array and which is the right way to do it?

Here is my code:

var SomeModel = Backbone.Model.extend({

   defaults : {
     id:null,
     name:'',
     order:null,
     isRequired:null,
}

initialize : function(options) {
    if(options.listPropertyValue !== undefined) {
        this.set('collectionPropertyValue', new PropertyValueCollection(options.listPropertyValue))
    }

    // I thought of doing this. Don't know if it's the right thing to do

    // this.unset('listPropertyValue', { silent: true });

}

My concern is not only how to do it, but how to do it in a proper Backbone way.

Was it helpful?

Solution 2

I finally did it. I used the same code I published but it didn't work until I used backbone with version 1.1.2 (I was using 1.0.0 or similar).

var SomeModel = Backbone.Model.extend({

   defaults : {
        id:null,
        name:'',
        order:null,
        isRequired:null,
    }

    initialize : function(options) {
        if(options.listPropertyValue !== undefined) {
            this.set('collectionPropertyValue', new PropertyValueCollection(options.listPropertyValue));
        }

        this.unset('listPropertyValue', {
            silent : true
        });
    }
}

OTHER TIPS

(I assume you're getting this data from an API somewhere.)

You should define a parse method in your model to return only the data you're interested in:

parse: function(response){
  return _.omit(response, "listPropertyValue");
}

Backbone will do the rest for you: every time it receives API from the data it will call parse automatically.

For more info: http://backbonejs.org/#Model-parse

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top