How to mock static method call by constructor?

How do I call fetch method from within a render method in Backbone.js?

  • Hi I am trying to call fetch method to  get a collection of models from inside a render method but the before  the fetch method gets called other lines of the render method are  executed and finally the fetch method is called. Can  anyone help me to pause the lines following the fetch method till all  the models are fetched and then complete the render method. Thanks

  • Answer:

    You could override the fetch method and trigger callbacks on success and error of your fetch method. Check the code below... Model var TestModel = Backbone.Model.extend({ fetch: function () { var self = this; var fetchOptions = { success: function (model, data) { self.trigger('TestView:ResponseReceivedSuccess', data); }, error: function (model, error) { self.trigger('TestView:ResponseReceivedError', error); }, type: 'GET', contentType: 'application/json', async: false }; self.trigger('TestView:RequestSent'); Backbone.Model.prototype.fetch.call(self, fetchOptions); } }); View var TestView = Backbone.View.extend({ initialize: function () { this._bindModelChangeEvents(); this.model.fetch(); }, _bindModelChangeEvents: function () { var self = this; this.model.on('TestView:ResponseReceivedError', function () { // error while fetch }); this.model.on('TestView:ResponseReceivedSuccess', function (data) { // do something with your data here }); } });

Yasser R Shaikh at Quora Visit the source

Was this solution helpful to you?

Other answers

The problem is the fetch method is a asynchronous one. So your remaining piece of code inside render function gets executed and asynchronously the fetch method gets executed. You can have a return soon after the fetch method is called and inside fetch onSuccess execute the render function.

Rohith Menon

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.