Backbone Marionette 3 app:集合提取返回空数组

时间:2017-05-23 14:29:57

标签: javascript backbone.js marionette

我遇到的问题是,无论何时在调用listaCollection.fetch()之后调用listaCollection.toJSON(),它都会返回一个空数组。如果我在fetch方法的成功回调中执行console.log(data.toJSON()),我将能够看到它正确地获取它。如果我对骨干/牵线木偶很新,那么任何帮助都会非常感激。这是代码。

import Bb from 'backbone';
import Mn from 'backbone.marionette';
import template from '../templates/ListasTemplate.jst';

const ListaCollection = Bb.Collection.extend({
  url: "http://localhost:3000/api/v1/lista/all",
  parse(data) {
    return data.lista;
  }
});

const listaCollection = new ListaCollection();

listaCollection.on("change", function() {
  reset();
});

listaCollection.fetch({
  success(data) {
    console.log(data.toJSON());
  }
});

const ListasView = Mn.View.extend({
  collection: listaCollection,
  className: "mdl-grid",
  regions: {
    listasContainer: "#listas-container"
  },
  template: template
});

export default ListasView;

这是我的模板:

<% _.each(items, function(item) { %>
  <div class="mdl-cell mdl-cell--6-col">
    <div class="demo-card-wide mdl-card mdl-shadow--2dp">
      <div class="mdl-card__title">
        <h2 class="mdl-card__title-text"><%= item.titulo %></h2>
      </div>
      <div class="mdl-card__supporting-text">
        <%= item.descricao %>
      </div>
      <div class="mdl-card__actions mdl-card--border">
        <button class="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect show-modal">
          <i class="material-icons">arrow_forward</i>
        </button>
        <button class="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect">
          <i class="material-icons">mode_edit</i>
        </button>
        <button class="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect">
          <i class="material-icons">clear</i>
        </button>
      </div>
    </div>
  </div>
<% }) %>

1 个答案:

答案 0 :(得分:0)

  

我在listaCollectionfactory声明

中的parse方法中调用了jSON

好吧,parse方法的返回值被设置为集合中的数据。因此,如果您在toJSON内调用parse,则数据尚未设置,因此它将返回空数组。