Mootools类,json处理/函数未定义
Mootools Class, json processing / function not defined
如果您在这里看到一些您认为可以改进的地方,请告诉我!
问题:我试图通过一个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..');
},
});
onComplete
中this
的绑定是请求实例本身,而不是您原来的作用域。
有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
类赋值函数结合使用,但我们不要这样做:)
相关文章:
- 现有函数未定义
- jQuery$.post可以在chrome、safari中工作,但不能在FF中工作(声明成功回调函数未定义)
- AngularJS ng repeat显示原型函数未定义
- jQuery onclick 函数:未定义不是一个函数
- 函数未定义
- 为什么在jsfiddle中显示ReferenceError:函数未定义
- 函数未定义,实际定义时为
- 函数未定义的Javascript(Basic)
- ajax函数未定义
- 为什么window.onload函数未定义
- 模块模式:函数未定义
- 包含的javascript源代码通过PHP,onmousemove事件,函数未定义
- 单击链接时出现函数未定义错误
- AngularJS和Angular Snap:SSnap构造函数未定义
- 在Node.js中,从同一文件中的另一个函数引用一个函数会导致'ReferenceError:-函数-未定义
- symfony trick javascript函数未定义
- 不断获取JS函数未定义错误
- AngularJS HTTP 资源 - 响应函数未定义
- 函数未定义,参数格式
- JavaScript 中的函数未定义