Sta*_*boy 0 javascript mootools json
如果你在这里看到一些你认为可以改进的东西,请告诉我!
问题:我正在尝试通过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..');
},
});
Run Code Online (Sandbox Code Playgroud)
结合this在onComplete一个请求是请求实例本身,而不是你原来的范围.
您可以使用3种模式.
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();
},
Run Code Online (Sandbox Code Playgroud)
你可以使用function.bind装饰器来改变回调中的范围:
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();
},
Run Code Online (Sandbox Code Playgroud)
这会跳过anon函数创建.
getObj: function (callThis) {
new Request.JSON({
method: 'get',
url: callThis,
onRequest: function () {
console.log('Loading: ' + callThis);
},
onComplete: this.processObj.bind(this)
}).send();
},
Run Code Online (Sandbox Code Playgroud)
在偏好方面:我选择#1因为它具有最小的性能足迹,它是首选的mootools方式[tm].然后可能#3为最佳代码组织.
有一种第四种方式与binds来自mootools 的类mutator 一起- 更多,但让我们不这样做:)
| 归档时间: |
|
| 查看次数: |
321 次 |
| 最近记录: |