Domanda

Sono nuovo di moootools e sto creando una classe template, questo è il mio codice -

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(); 
  }

});

Quello che voglio fare è questo:

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

Il problema è quando io chiamo questo codice:

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

Non ricevo la mia oggetto Modello attuale, sto ottenendo è 'definito'.
Come posso fare questo chainable?

È stato utile?

Soluzione

È in corso una chiamata asincrona all'interno della funzione get. La richiesta può richiedere 100ms, 1s o 10s e per il momento le finiture funzione get e ritorni, la richiesta sarà ancora in sospeso. Invece quello che dovete fare è, passare una funzione di callback per get e chiamata che in caso di successo.

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

Si noti che non si restituisce nulla dalla funzione get. Un esempio modo per richiamare questo sarebbe:

tpl.get('component', function(responseText) { alert(responseText); });

Altri suggerimenti

La funzione get manca un valore di ritorno. Se si desidera che funzioni a catena è necessario restituire l'oggetto stesso:

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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top