0

Hello I have some functionality in my backbone application, that allows the user to make a selection via a select menu and that choice fires a get request, the response is added to a collection,

this.archived.fetch({
    success:function() {
        this.archived.each(function(model){
            if(model.get('organisation_id') == $('.js-filter-by-organisation').val()){
                model.set('visible', true);
            } else if($('.js-filter-by-organisation').val() == "all")         {
                model.set('visible', true);
            }

            this.collection.add(model);
        });
    }
});

My problem is that when I then try and use the models added to the collection some of the attributes are the wrong type. For example in an archived model I have an attribute called organisations this should be a model, but when I run the fetch and then look at the results in the collection organisations is an object, however on my model I set this attribute to be an model on initialization.

Am I doing something wrong when I fetch from server, and add the results to my collection?

Evgeniy
  • 2,915
  • 3
  • 21
  • 35
Udders
  • 6,914
  • 24
  • 102
  • 194
  • It seems like you need to override the model's set attribute, to make a "new organization" with the raw data, OR override the whole collection's fetch method to parse the answer there. – Ofer Haber Apr 21 '15 at 14:25
  • On a sidenote, you seem to be doing the same in your `if` `else` constructs...setting `model.set('visible', true);` – Sandeep Nayak Apr 22 '15 at 07:08

1 Answers1

0

If you're using plain Backbone, you need to implement the 'parse( )' function in your Model on which you invoke fetch.

Per definition, this function is used to parse the data returned from your back-end after invoking fetch() or save().

See the docs for more details

If you're willing to try out some Backbone plugins that could take this burden in charge, I suggest you take a look at Backbone Relational.

kyiu
  • 1,926
  • 1
  • 24
  • 30