2013-01-22 18 views
1

我有一個返回一組物體的服務。一件事只需要一個id和一個name。我想加載到Ext.tree.Panel。目前,我已經定義了一個模擬服務典型響應的數據存儲。你可以玩一個演示JSFiddle here。包括以下如何填充Ext.data.TreeStore沒有孩子或葉信息?

代碼以及:

Ext.define('Thing', { 
    extend: 'Ext.data.Model', 
    fields: ['id', 'name'], 
}); 

var store = Ext.create('Ext.data.TreeStore', { 
    model: 'Thing', 

    // example service response (in reality, this would be JSON) 
    root: { 
     children: [ 
      { 
       id: 1, 
       name: 'Thing 1', 
      }, 
      { 
       id: 2, 
       name: 'Thing 2', 
      }, 
      { 
       id: 3, 
       name: 'Thing 3', 
      }, 
     ], 
    }, 

    listeners: { 
     append: function(thisNode, newChildNode, index, eOpts) { 
      if(!newChildNode.isRoot()) { 
       newChildNode.set('text', newChildNode.get('name')); 
      } 
     }, 
    }, 
}); 

Ext.create('Ext.tree.Panel', { 
    renderTo: Ext.getBody(), 
    store: store, 
    rootVisible: false, 
}); 

正如你所看到的,該服務僅返回一個東西的idname,像childrenleaf沒有樹節點信息,這是一個Ext.data.TreeStore通常希望。

我根本無法改變服務作爲迴應返回的內容。我喜歡我可以調用服務並獲得一系列平面事物,而不需要額外的樹節點信息。有很多應用程序在與此服務交談時根本不需要這些數據,而且我沒有獲得權限的許可,即可以對其進行更改。

不幸的是,沒有在響應每一件事情中定義的children元素,分機引發了以下錯誤,當我試圖展開節點(可以在的jsfiddle產生這樣自己):

Uncaught TypeError: Cannot call method 'indexOf' of undefined 

所以,我的問題是:如何避免在我的回覆中發回children(或leaf)並解決此錯誤?我只想把我的東西加載到樹中並且可擴展(是的,它們不能成爲葉子)。

回答

0

自己添加這些信息!

小例子(您可以輕鬆地嘗試在控制檯從您的瀏覽器):

a = {b:23}; 
a.c = 25; 
//a is now the same like {b:23, c:25} 

在商店的afterRequest法例如,你可以做以下操作:

proxy: { 
    type: 'ajax', 

    url: 'xxx', 

    listeners: { 
     exception: function(proxy, response, options) { 
      //error case 
     } 
    }, 

    afterRequest: function(request, success) { 
     var resText = request.operation.response.responseText, 
      allThings = Ext.decode(resText), //Decodes (parses) a JSON string to an object 
      things = allThins.children,  //Now we have an object an we can do what we want... 
      length = things.length; 

     for (var i = 0; i < length; i++) { 
      things[i].leaf = true; 
      things[i].expanded = true; 
     } 

     this.setRootNode(allThings); 
    } 
} 

這只是一些僞代碼,但它應該工作! 設置一個調試器語句Link),看看你真的回來了!

我希望這有助於!

0

您可以嘗試迭代您的響應存儲並創建子節點。 然後你的孩子追加到根節點

store.each(function(rec) { 
    var childNode ; 
    //Create a new object and set it as a leaf node (leaf: true) 
    childNode = Ext.create('Model_Name', { 
     id: rec.data.id, 
     name: rec.data.name, 
     text : rec.data.name, 
     leaf : true, 
    }); 
    // add/append this object to your root node 
    treepanel.getRootNode().appendChild(childNode); 
}); 

檢查this link更多細節