0

我有一个插件,可以通过 ajax 从远程源或存储在内存中的本地数据源获取数据。我在将集合数据获取到本地数据视图时遇到问题(集合为空,请参见第 53 行)。本地数据在集合中可用,因为第 37 行的 console.log 显示了数据。来自远程和本地源的数据是具有相同结构/层次结构/值的 JSON。

如何从本地源获取数据以供视图使用,以便在模板中呈现它?

// pluginname
$.fn.pluginname = function(options) {
var defaults = {
  source: 'external', // external (fetch data from url) or internal (grab data from memory)
},
settings = $.extend({}, defaults, options);  

// define the model
item = Backbone.Model.extend();

// define the collection
items = Backbone.Collection.extend({
  model: item,
  page: settings.page,
  // url to request when fetch() is called
  url: function() {
    return 'http://www.sample.com/feed.json'
  },
  parse: function (response) {
    return response;
  },
  // overwrite the sync method to pass over the same origin policy
  sync: function (method, model, options) {
    var that = this;
    var params = _.extend({
      type: 'GET',
      dataType: 'jsonp',
      url: that.url(),
      processData: false
    }, options);
    // remote source of data
    if (settings.source == 'remote'){
      return $.ajax(params);
      // local source of data (data read from memory via $.data)
    } else if (settings.source == 'local'){
      //return JSON.stringify($('body').data('someid'));
      return console.log(JSON.stringify($('body').data('someid'))); // logs data correctly in console
    };
  }
});

// define the view
itemsView = Backbone.View.extend({
  initialize: function () {
    console.log('itemsView initialize')
    _.bindAll(this, 'render');
    // create a collection
    this.collection = new items;
    // fetch the collection and call render() method
    var that = this;
    this.collection.fetch({
      success: function () {
        console.log(that.collection); // fails (returns empty) for json data from local source
        that.render();
      },
      error: function () {
        console.log('collection fetch error'); // does not get logged
      }
    });
  },
  // define template
  template: _.template($('#templateid').html()),
  // render function
  render: function(){
    $(this.el).html(this.template({
      items: this.collection.toJSON()
    }));
  },
});

var app = new itemsView({
  // define the el where the view will render
  el: $('.'+settings.render_selector+'')
});

}; // ends plugin function
4

1 回答 1

1

返回 JSON:

} else if (settings.source == 'local'){
    var json = JSON.stringify($('body').data('someid')));
    options.success(json);
};
于 2013-09-13T11:50:07.733 回答