0

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.

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
madtyn
  • 1,469
  • 27
  • 55
  • It looks like the parse() solution doesn't work at all. It doesn't even pass through the parse() method when retrieving data from server. Though, it does with the unset() method in initialize(). It seems to work, but finally I find the same when I retrieve a big data list from AJAX. – madtyn Mar 21 '14 at 12:15

2 Answers2

1

(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

David Sulc
  • 25,946
  • 3
  • 52
  • 54
  • I'm getting the _options_ data object from the Java Controller and it is transformed from Java to JSON with Jackson. I'm trying this and I'll let you know how does it work. – madtyn Mar 12 '14 at 09:56
  • parse() is not ever called because the data comes from AJAX request, not fetch() or save(). This has to be done in initialize(). – madtyn Mar 29 '14 at 17:12
0

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
        });
    }
}
madtyn
  • 1,469
  • 27
  • 55