ExtJs TreePanel Проблема управления памятью - PullRequest
0 голосов
/ 11 августа 2011

Панель управления деревом и памятью магазина

Привет, Я новичок в Ext Js и не могу найти ответ на свою проблему. У меня есть TreePanel и меню с некоторыми фильтрами. Когда я меняю фильтры, мне нужно перезагрузить дерево. Поэтому у меня есть слушатель в меню, когда выбор завершен, он вызывает loadElementContent. Контент загружается правильно каждый раз, единственная проблема заключается в том, что потребление памяти только увеличивается и увеличивается. Я пытался уничтожить каждый узел при удалении его из дерева, я пытался удалить элементы из хранилища с помощью elemStore.removeAll (), но, похоже, ничего не работает. Любая помощь приветствуется. Ниже код:

Контроллер дерева:

Ext.define('myController.Index', {
  extend: 'Ext.app.Controller',
  stores: ['Elements'],
  models: ['Element'],
  views: ['index.MainTabPanel', 'GenericTree'],

  refs: [
         {
           ref: 'elementsTree',
           selector: 'maintabpanel generictree[name=myTree]'
         }
       ],

  init: function() {
    this.control({
      'viewport > maintabpanel': {
        render: this.onMainTabPanelRender,
        myEvent: this.buttonHandler
      }
    });
  },
  setProxyParameters: function(proxy) {
    proxy.extraParams.filter_key = 12;
    return proxy;
  },
  onMainTabPanelRender: function() {
    this.on('onElemStoreLoadSucces', this.onElemStoreLoadSuccess);
  },
  loadElementContent: function() {
    var elemStore = this.getElementsStore();
     elemStore.setProxy(
        this.setProxyParameters(
            elemStore.getProxy()));
     elemStore.load({
      scope: this,
      callback: function(elements, elOperation, elSuccess) {
        if (elSuccess) {
          this.fireEvent('onElemStoreLoadSucces');
        } else {
          Ext.Error.raise(new Mytils.JSONError
            (elemStore.getProxy(), elOperation));
        }
      }
    });
  },
  onElemStoreLoadSuccess: function() {
    this.loadTree(this.getElementsStore().getRange());
  },
  loadTree: function(elements) {
    var root = this.getElementsTree().getRootNode();
    this.clearChildNode(root);
    this.appendChildrentToNode(root, elements);
    console.log(root);
  },
  clearChildNode: function(node) {
    console.log('removing children');
    while (node.firstChild) {
      node.removeChild(node.firstChild);
    }
  },
  appendChildrentToNode: function(root, elements) {
    console.log('appending children');
    Ext.Array.each(elements, function(element) {
      element.set('ischecked', 0);
      element.set('name', element.get('element_id'));
      element.set('leaf', true);
      root.appendChild(element);
    });
  },  
  buttonHandler: function() {
    this.loadElementContent();
  }
});

Прокси-сервер:

/**
 * This class is merely an Ext.data.proxy.Ajax, using a JSON reader
 * and writer, and with some preset config properties.
 */
Ext.define('myUtils.MyAjaxProxy', {
  extend: 'Ext.data.proxy.Ajax',
  alias: 'proxy.myajax',

  constructor: function (config) {
    // Preset some config options, if not specified differently.
    Ext.applyIf(config, {
      // By default, the JSON requests are sent with a 'start', 'page' and 'limit' parameters.
      // As long as data is retrieved all at once, these are not needed, so remove them:
      startParam: undefined,
      pageParam: undefined,
      limitParam: undefined,
      // By default, a parameter with the name "_dc" ("disable caching") and a random value is added to each request,
      // to prevent caching of the response and enforce each request to be handled by the server.
      // Set this config parameter to false to eliminate the _dc parameter and thus enable caching:
      // noCache: false,

      reader: {
        type: 'json',
        // The names of the fields in a JSON response containing the success/failure status,
        // and (in case of error) the corresponding error message.
        successProperty: 'success',
        messageProperty: 'error_msg'
      },

      writer: {
        // Configure the writer to only POST modified fields.
        writeAllFields: false
      }
    });

    myUtils.MyAjaxProxy.superclass.constructor.call(this, config);
  }
});

Магазин:

Ext.define('myStore.Elements', {
  extend: 'Ext.data.Store',
  requires: ['myUtils.GsaAjaxProxy'],
  model: 'myModel.Element',
  //autoLoad: true,
  proxy: {
    type: 'myajax',
    url: getApiURL('getElements'),
    reader: {
      root: 'elements'
    }
  }
});

Модель:

Ext.define('myModel.Element', {
  extend: 'Ext.data.Model',
  fields: ['key',
      'element_key',
      'element_id',
      'element_value'
  ]
});

1 Ответ

0 голосов
/ 01 декабря 2011

Я не уверен, поможет ли это или нет, так как я не использую собственный прокси, но я просто определяю свой магазин следующим образом. Затем для перезагрузки данных я просто вызываю myTree.getStore (). Load (); Я не видел проблем с памятью

store=Ext.create( 'Ext.data.TreeStore',//
        {
            id:ts_id,
            storeId:ts_id,
            remoteSort:false,model:dv_model_id,
                    folderSort: true,
                    sortOnLoad:false,

            proxy: 
            {
                type: 'rest',
                url: this.url
            },
            extraParams:{season_id: proxy_sesaon_id }
            ,listeners:
            {
                load:{scope:this,fn:function()
                {
                    //default is to load as collapsed: this keeps all folders open all the time
                    this.expandAll();   
                }}
            }
...