2013-06-12 4 views
0

Я только начинаю с Sencha Touch и работаю над версией 2.2.1. По какой-то причине я не могу заставить мой локальный json правильно разбираться. Я знаю, что это не проблема ответа, потому что я вижу json в своем инструменте разработчиков Chrome.Не удается разобрать локальный json

Вот мой store

Ext.define('MyApp.store.Tasks', { 
    extend: 'Ext.data.Store', 
    requires: [ 
     'MyApp.model.Task' 
    ], 

    config: { 
     autoLoad: true, 
     storeId: 'tasksStore', 
     model: 'MyApp.model.Task', 
     proxy: { 
      type: 'ajax', 
      url: 'tasks.json', 
      reader: { 
       type: 'json', 
          rootProperty: 'tasks' 
      } 
     } 

    } 
}); 

Вот мой Model

Ext.define('MyApp.model.Task', { 
    extend: 'Ext.data.Model', 

    config: { 
     fields: [ 
      { name: 'id', type: 'int' }, 
      { name: 'task', type: 'string', defaultValue: 'task' } 
     ] 
    } 
}); 

Я использую Jasmine, чтобы проверить мой магазин. Вот мой спецификации

describe('MyApp.store.Tasks', function() { 
    it('Number of tasks should be four', function() { 
    var store = Ext.create('MyApp.store.Tasks'); 

    expect(store.getCount()).toBe(4); 

    }); 
}); 

И вот мой пример файла json. Он находится в том же каталоге, что и файл index.html Sencha, который является корневым каталогом.

{ 
    "tasks":[ 
     { 
     "task":"Some Product", 
     "id":0 
     }, 
     { 
     "task":"Another Product", 
     "id":1 
     }, 
     { 
     "task":"A third product", 
     "id":2 
     }, 
     { 
     "task":"A fourth product", 
     "id":3 
     } 
    ] 
} 

Это из-за проблем с экземплярами? Или я пропустил здесь какую-то критическую вещь? Я пробовал jsonp для типа прокси, но для ответа нужен обертка, и я не совсем понимаю, как это сделать. Я тестирую как Safari, так и Chrome, к сожалению, единичный тест не работает в обоих браузерах.

Спасибо!

ответ

1

Загрузка магазина асинхронна, поэтому вы не можете получить доступ к своим данным сразу после их создания.

Чтобы знать, когда магазин был загружен, вы можете слушать на load event магазина:

var store = Ext.create('MyApp.store.Tasks'); 

// you cannot use the store's data yet 
// expect(store.getCount()).toBe(4); 

store.on('load', function(records, success) { 
    if (success) { 
     // here the store has been loaded 
     expect(store.getCount()).toBe(4); 
    } 
}); 

Или, вы можете также передать функцию обратного вызова к load method:

var store = Ext.create('MyApp.store.Tasks', {autoLoad: false}); 

store.load({ 
    callback: function(records, operation, success) { 
     if (success) { 
      // here the store has been loaded 
      expect(store.getCount()).toBe(4); 
     } 
    } 
}); 

сейчас , это означает, что вам также потребуется make your Jasmine test asynchronous:

describe('MyApp.store.Tasks', function() { 
    it('Number of tasks should be four', function() { 
     var result = null, 
      store = Ext.create('MyApp.store.Tasks'); 

     store.on('load', function(store, records, success) { 
      result = success; 
     }); 

     // using jasmine async... 
     waitsFor(function() { 
      return result !== null; 
     }); 

     // this functin will be executed when the one in waitsFor returns true 
     runs(function() { 
      expect(store.getCount()).toBe(4); 
     }); 
    }); 
}); 
+0

очень хороший объяснение! Спасибо! – javaCity

Смежные вопросы