murli2308 murli2308 - 6 months ago 42
Javascript Question

Stop emberjs to send request to server for loaded record

I am having a

customer
model and a
product
model

customer model

import DS from 'ember-data';
export default DS.Model.extend({
type: DS.attr('string'),
name: DS.attr('string'),
product: DS.hasMany('product')
});


product model

import DS from 'ember-data';
export default DS.Model.extend({
type: DS.attr('string'),
name: DS.attr('string'),
customer: DS.belongsTo('customer')
});


I load all the customer in
model()
hook of route.js as below

model() {
customers: this.store.findAll('customer'),
}


so as of now I have all the records of customer.

then using
findRecord
method I load perticular product as

this.store.findRecord('product', productId);


I call this on
click
of a
button
say Find Products, this is written in controller.js

now when I write in template as

{{product.customer.name}}


it send a get request to load the customer which is already loaded. I want to stop that request how I can do this ?

As per my knowledge


When we already have the record, store.findRecord will resolve immediately with cached data, but will send a request in the background to update the record and once the record is updated your template will show the new changes.


I want to stop that request.

Answer

I got the solution.

If we return false from shouldBackgroundReloadAll and shouldBackgroundReloadRecord, then also ember will send background request if the model we are looking for is in belongsTo relationship.

In template I am calling customer name

{{product.customer.name}}

It is sending ajax request as it has belongsTo relationship.

I overriding the method findBelongsTo in the adapters/application.js. I am checking whether record is loaded or not if loaded then do not send request

findBelongsTo: function(store, snapshot, url, relationship) {
    var record = store.peekRecord(relationship.type, url);
    if(record){
      return new Ember.RSVP.Promise(function(resolve, reject) {
          // on success
          var r = Ember.copy(record._internalModel._data, true);
          r._id = record.id;
          var d ={ meta: {} };
          d[Ember.String.pluralize(relationship.type)] = [r];
          resolve(d);
          // on failure
          reject(null);
         });
    } else{
          url = this.buildURL(relationship.type, url, snapshot, 'findRecord');
          return this.ajax(url, 'GET');
    }
}
Comments