dojo声明构造函数:对象成员引用undefined

时间:2015-12-01 19:18:34

标签: javascript dojo dijit.tree

我不知道为什么我遇到麻烦,在下面一段代码的this.treeStore方法中引用类成员对象checkAcceptance

代码段(link to a running jsfiddle example...):

dojo.declare("at.delta.util.FolderConfigurator", null, {
    treeStore: null,
    treeModel: null,
    tree: null,

    constructor: function (/*string*/ jsonData) {
        this.treeStore = new dojo.data.ItemFileWriteStore({
        data: jsonData
        });
        this.treeModel = new dijit.tree.ForestStoreModel({
           store: this.treeStore // this.treeStore available, perfect no problems
        });  
        this.tree = new dijit.Tree({
           model: this.treeModel,
           showRoot: false,
           betweenThreshold: 5,
           dndController: "dijit.tree.dndSource",
           checkAcceptance: function ( /*Object*/ source, /*Array*/ nodes) {
               // Here comes the code for drag acceptance
               var currentNode = dijit.getEnclosingWidget(nodes[0]).item;
               var parentNode = this.treeStore.getValue(currentNode, 'parent'); // typeError: this.treeStore is undefined
               return (parentNode && parentNode.owners !== undefined);
        }
    }, "pnlTree");
  }

});

尝试拖动树的节点会导致firefox / firebug控制台出现以下错误:

  

TypeError:this.treeStore未定义

任何帮助将不胜感激:)

2 个答案:

答案 0 :(得分:1)

问题是checkAcceptance函数中的this关键字的范围是dijit.Tree窗口小部件,而不是您自己的窗口小部件。只需在构造函数范围级别的某处添加var self = this;,然后在超出范围时使用self而不是this来引用。

答案 1 :(得分:1)

这是因为 this 指的是 this.tree 而不是主要对象。 用这个 -

 dojo.declare("at.delta.util.FolderConfigurator", null, {
    treeStore: null,
    treeModel: null,
    tree: null,

    constructor: function (/*string*/ jsonData) {
        var _this = this;
        this.treeStore = new dojo.data.ItemFileWriteStore({
        data: jsonData
        });
        this.treeModel = new dijit.tree.ForestStoreModel({
           store: _this.treeStore // this.treeStore available, perfect no problems
        });  
        this.tree = new dijit.Tree({
           model: _this.treeModel,
           showRoot: false,
           betweenThreshold: 5,
           dndController: "dijit.tree.dndSource",
           checkAcceptance: function ( /*Object*/ source, /*Array*/ nodes) {
               // Here comes the code for drag acceptance
               var currentNode = dijit.getEnclosingWidget(nodes[0]).item;
               var parentNode = _this.treeStore.getValue(currentNode, 'parent'); // typeError: this.treeStore is undefined
               return (parentNode && parentNode.owners !== undefined);
        }
    }, "pnlTree");
  }

});