-1

I have following kind of collection

[
   {
     "id": "2324324",
     "name": "name",
     "type": "type",

 },
{
    "id": "59980",
    "name": "name",
    "type": "type",

}

]

model:

define(['underscore', 'backbone'], function(_, Backbone){
//Define Alert model with default properties and value
var abcModel = Backbone.Model.extend({
    idAttribute:"_id",
    defaults:{
       // My properties
    },
    initialize:function(){          

    }
});
return abcModel;
});

collection

 define(['underscore', 'backbone', 'models/abcModel', 'app/utils'], function(_, Backbone, abcModel, Utils) {

    var self;
    //List of Alerts stored in Backbone Collection
    abcListCollection = Backbone.Collection.extend({
        model: abcModel ,
        initialize: function() {           
            self = this;
            this.model=abcModel ;
        },

       fetchData: function(obj) {           
            add=true;
            var data = {
                "method": "method name",
                "params": {
                    param1:"param1",
                    param2:"param2"
                }
            }

            Utils.Ajax.post(Utils.WebAPI.WebAPIServer, data, function(response, textStatus, jqXHR) {                                
                obj.success.call(self.collection, response);
            }, 'json', function(err) {
                console.log(JSON.stringify(err));
                obj.error.call(err);
            }, "loading");

        },
        collection: {}
         });
        return abcListCollection;
});

view

 define(['jquery', 'underscore', 'backbone', 'text!views/abcView/abcListView.html','views/abcView/ListTemplate' ,'app/utils', 'collection/abcListCollection'], function($, _, Backbone, tmpl_abcummaryView, abcListView, Utils, abcListCollection) {

 var abcListView = Backbone.View.extend({
// Setting the view's template property using the Underscore template method        
template: _.template(tmpl_abcummaryView),
// View constructor
initialize: function() {            
    abcCollection= new abcListCollection();
        mainRouter.collections.abc= new abcListCollection();          
},
// View Event Handlers
events: {

},
// Renders the view's template to the UI
render: function() {
    var self=this;
    this.$el.html(this.template({data: this.templateData}));   
    abcCollection.fetchData({
                success: function (collection, response) {                        
                    _.each(collection, function (obj) {                             
                        mainRouter.collections.abc.add(obj);                                                       
                    })
                },
                error: function (err) {
                    console.log("error");
                }
        });         
    var model1=mainRouter.collections.abc.get(2324324);
    // Maintains chainability
    return this;
}
});
return abcListView;
 });

var model1=mainRouter.collections.abc.get(2324324); But it is returning undefined.

Priya
  • 1,453
  • 4
  • 29
  • 55

2 Answers2

0

You could try

mainRouter.collections.abc.findWhere( { id : 2324324 });

However, it seems that your timing could also be out.

the .fetchData function would be an asynchronous call, meaning that the success function would actually execute after the line

var model1 = mainRouter.collectins.abc.get(2324324);

Put a debug breakpoint on the above line, and also the success function - and see which one executes first.

blorkfish
  • 21,800
  • 4
  • 33
  • 24
  • mainRouter.collections.abc.findWhere( { id : 2324324 }); is undefined and i have used mainRouter.collections.abc.findWhere( { id : 2324324 }); in router and in console it is available. – Priya May 15 '14 at 05:22
  • Have you ruled out that is is a timing issue ? If you put two breakpoints in your code - one on _.each(collection, function (obj), and the other on var model1=mainRouter.collections.abc.get(2324324); - do they fire in the correct order ? – blorkfish May 15 '14 at 05:30
  • yes _.each(collection, function (obj) is in view and using collection from there i am adding elements to mainRouter.collections.abc and then in router file i am doing mainRouter.collections.abc.findWhere( { id : 2324324 }); and before that i have console.log(mainRouter.collections.abc) which returns all data in collection – Priya May 15 '14 at 05:33
0

Your fetchData is a asynchronous function. It would be executed in the event loop after that async call is resolved. Your code is not blocking at that call. It just goes over that and executes the render function completely. After some time, when that call would return and your success callback would be called, you get something in your collection.

Putting the code of getting the model from the collection is right and should be put in a callback after you have added models to the collection.

see Collection get http://backbonejs.org/#Collection-get

so one way to do is to write:

success: function (collection, response) {                        
                    _.each(collection, function (obj) {                             
                        mainRouter.collections.abc.add(obj);                                                       
                    })
                 var model1 = mainRouter.collectins.abc.get(2324324);
                },

However it does not seem right to use your model in your view. but that is the design issue that you have to think about.

Also, i think that you should read a little more about Javascript event driven architecture. I have written a simple blog : Learning Javascript

Ashish Negi
  • 5,193
  • 8
  • 51
  • 95