骨干模型是纯文本文件。怎么取?

时间:2014-03-21 18:42:13

标签: backbone.js backbone-model

我有一个包含纯文本文件的模型文件。例如,Github Gists有这个url结构:https://gist.githubusercontent.com/140bytes/962807/raw/dfb480a5038214d152544bddb412dfe2e8656413/LICENSE.txt

要做到这一点,我应该覆盖fetch / save / etc,还是应该覆盖模型的同步?

var File = Backbone.Model.extend({
  path: '',
  contents: '',
  initialize: function(options) {
    this.path = options.path || '';
  },
  fetch: function() {
    // Do I override fetch/save/etc?
    $.get(this.path).done(function(contents) {this.contents = contents});
  },
  sync: function (method, model, options, error) {
    // Or do I override sync?
  }
});

1 个答案:

答案 0 :(得分:5)

您可以稍微覆盖parsefetchurl方法:

var File = Backbone.Model.extend({
  url: function(){
    return this.get('path')
  },

  // call original Backbone.Model#fetch with `dataType` equal `text` for $.ajax
  fetch: function(options){
    options = _.extend(options || {}, {
      dataType: 'text'
    });
    this.constructor.__super__.fetch.call(this, options);
  },

  // store response in content attribute
  parse: function(response){
    return {content: response};
  }
});

在这种情况下,您的代码将更加惯用,您将获得Backbone本机方法的所有好处(获取,请求和同步事件,更改事件等的成功和错误回调)。您可以像使用它一样使用它:

var someFile = new File({
  path: 'http:/example.com/someFile.txt'
});

someFile.fetch({
  success: function(){
    console.log(someFile.get('content'); // => content of someFile.txt
  }
});