Вопрос

I have a model File which contains a plain text file. For example Github Gists have this url structure: https://gist.githubusercontent.com/140bytes/962807/raw/dfb480a5038214d152544bddb412dfe2e8656413/LICENSE.txt.

To do this, should I override fetch/save/etc, or should I override the model's sync?

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?
  }
});
Это было полезно?

Решение

You can just override parse, fetch and url method a little:

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};
  }
});

In this case your code will be more idiomatic and you will have all benefits of Backbone native methods (success and error callbacks to fetch, request and sync events, change events etc). You can use it like:

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

someFile.fetch({
  success: function(){
    console.log(someFile.get('content'); // => content of someFile.txt
  }
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top