0

I am new to moootools and I am creating a Template class,This is my code -

var Template = new Class({
  Singleton : true,
  template : '',

  /* gets the component type template */
  get : function(componentType){
    var tplUrl = Core.getUrl('backend') + 'response/' + componentType + '/get_template.php',
        that = this,
        request = new Request({url: tplUrl, method : 'get',onSuccess : function(responseText){
          that.template = responseText; 
          return that;
        }}).send(); 
  }

});

What I want to do is this :

var tpl = new Template();
tpl.get('component').setTemplateData({name:'yosy'});

The problem is when I am calling this code :

var tpl = new Template();
console.log( tpl.get('component') );

I am not getting my current Template object,I am getting is 'undefined'.
How I can make this chainable?

Yosi
  • 2,936
  • 7
  • 39
  • 64

2 Answers2

1

You are making an asynchronous call inside the get function. The request may take 100ms, 1s or 10s and by the time the get function finishes and returns, the request will still be pending. Instead what you need to do is, pass a callback function to get and call that on success.

get: function(componentType, successCallback) {
    var request = new Request({
        ..,
        onSuccess: successCallback
    }).send();
}

Note that you are not returning anything from the get function. One example way to invoke this would be:

tpl.get('component', function(responseText) { alert(responseText); });
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • to make it chainable he can also turn into into a synchronous request, although it defeats the purpose :) – Dimitar Christoff Aug 24 '10 at 16:34
  • I've stopped recommending the synchronous option :) but good alternatives would be this concept of [futures and promises](http://en.wikipedia.org/wiki/Futures_and_promises), and the [async method queues](http://www.dustindiaz.com/async-method-queues/) by Dustin Diaz. – Anurag Aug 24 '10 at 16:51
-1

Your get function is missing a return value. If you want functions to chain you should return the object itself:

get : function(componentType){
var tplUrl = Core.getUrl('backend') + 'response/' + componentType + '/get_template.php',
    that = this,
    request = new Request({url: tplUrl, method : 'get',onSuccess : function(responseText){
      that.template = responseText; 
      return that;
    }}).send(); 

    return this;
}
Riwen
  • 1
  • Not sure if returning the current object or the request will be on any help here. `get` probably needs a callback for when the component loads. – Anurag Aug 24 '10 at 15:41
  • But I want to return the object when I done loading the request. – Yosi Aug 24 '10 at 15:47