Mootools类,json处理/函数未定义

Mootools Class, json processing / function not defined

本文关键字:函数 未定义 处理 json Mootools      更新时间:2023-09-26

如果您在这里看到一些您认为可以改进的地方,请告诉我!

问题:我试图通过一个mootools类来实现处理一些Json数据的基本结构。我目前遇到的是,当我调用"this.processObj"时,我收到"processObj未定义"

代码:

this.runSomeJson= new Class({
    Implements: [Options, Events],
    options: {
        contentInfo: false,
    },
    initialize: function(element, options) {
        this.element = document.id(element);
        if (!this.element) return;
        this.setOptions(options);
        this.setBasicInfo();
    },
    setBasicInfo: function () {
        var callThis = 'somegenericurl';
        this.getObj(callThis);
    },
    getObj: function (callThis) {
        var jsonReq = new Request.JSON({
          method: 'get',
          url: callThis,
          onRequest: function () {
            console.log('Loading: ' + callThis);
          },
          onComplete: function(thisObj){
            //console.log(thisObj);
            this.processObj(thisObj);
          }
        }).send();  
    },
    processObj: function (thisObj) {
        console.log('in process..');
    },
});
请求的onCompletethis的绑定是请求实例本身,而不是您原来的作用域。

有3种模式可以使用。

1.保存引用

getObj: function (callThis) {
    var self = this;
    new Request.JSON({
      method: 'get',
      url: callThis,
      onRequest: function () {
        console.log('Loading: ' + callThis);
      },
      onComplete: function(thisObj){
        // call it on the self reference
        self.processObj(thisObj);
      }
    }).send();  
},

2.绑定匿名函数

您可以使用函数.bind decorator来更改回调中的作用域:

getObj: function (callThis) {
    new Request.JSON({
      method: 'get',
      url: callThis,
      onRequest: function () {
        console.log('Loading: ' + callThis);
      },
      onComplete: function(thisObj){
        //console.log(thisObj);
        this.processObj(thisObj);
      }.bind(this) // change scope, inner this becomes the outer this as well.
    }).send();  
},

3.移动到类上的方法并直接绑定

这将跳过anon函数的创建。

getObj: function (callThis) {
    new Request.JSON({
      method: 'get',
      url: callThis,
      onRequest: function () {
        console.log('Loading: ' + callThis);
      },
      onComplete: this.processObj.bind(this)          
    }).send();  
},

在偏好方面:我会选择#1,因为它的性能占用最小,它是首选的mootools方式[tm]。那么可能是最佳代码组织的第三名。

还有第四种方法与mootools中的binds类赋值函数结合使用,但我们不要这样做:)