Ajoy
Ajoy

Reputation: 1848

Return search promise

I am building a cordova app with Ember. An issue that I have run into is that Ember does not return a promise when the user changes input, but hangs when the search is processed.

App.SearchController = Ember.ObjectController.extend({
  name: "",
  products: null,
  loading : false,
  searchProducts: function(){
    this.set("loading", true);
    controller = this;
    var promise = new Ember.RSVP.Promise(function(resolve, reject){
        var productArray = App.Products.byString(controller.get("name").toLowerCase());
        resolve(productArray);
    }).then(function(arr){
        controller.set("products", arr);
        controller.set("loading", false);
    });
  }.observes("name")
});

In my search template, this is the search box :

{{input type="search" placeholder="Search products" class="form-control" value=name autofocus="autofocus"}}

But every time the user changes the input, the router blocks till the name is searched for and the results are displayed immediately, without the spinner spinning (if loading == true).

I think that I have implemented the Promise incorrectly. In that case, please do tell me where I am wrong.

UPDATE 1

"byString" : function(strSearch){
    products = JSON.parse(localStorage.getItem("data"));
    var productArray = [];
    var idlist = products.product_ids;
    var len = idlist.length;
    for(var i = 0; i < len; i++){
        var str = idlist[i].name.toLowerCase();
        if(str.match(strSearch)!=null && strSearch!=""){
            productArray.push(idlist[i]);
        }
    }
    return productArray;
}

UPDATE 2

The lag that I am experiencing is due to javascript processing the array. Can this not be handled by a Promise? Is there a way to prevent the router from blocking and wait for javascript to return its result, displaying the loader in the meanwhile?

Upvotes: 0

Views: 114

Answers (2)

Kingpin2k
Kingpin2k

Reputation: 47367

I'm not sure if I see a point in implementing a promise here, it doesn't look like you're making any sort of asynchronous call.

That being said you are probably just experiencing rendering lag, or javascript lag, which will cause animated images etc to slow to a crawl.

You can prove this by adding a timeout before resolving.

  var promise = new Ember.RSVP.Promise(function(resolve, reject){
       Em.run.later(function(){
          var productArray = App.Products.byString(controller.get("name").toLowerCase());
          resolve(productArray);
       }, 5000);
    }).then(function(arr){
        controller.set("products", arr);
        controller.set("loading", false);
    });
  }.observes("name")

Upvotes: 1

AniZ
AniZ

Reputation: 31

Look at the PromiseProxyMixin http://emberjs.com/api/classes/Ember.PromiseProxyMixin.html

Upvotes: 1

Related Questions