0

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?
  }
});
000
  • 26,951
  • 10
  • 71
  • 101
  • Do you need to send the document back to the server? If you don't, use fetch. – jgillich Mar 21 '14 at 19:01
  • Can you clarify _"I have a model File which contains a plain text file"_? What do you mean by 'contains a plain text file'? Do you mean that the data for the model is in a text file? – T Nguyen Mar 21 '14 at 19:01
  • @TNguyen The File model has an attribute "contents" which will contain the contents of the plain-text file. The server is not responding with json, it is responding with plain text. I just want the model to stuff the response into the *contents* attribute rather than trying to parse the response as json – 000 Mar 21 '14 at 19:08
  • Yeah so in that case, what jgillich said. Just remember that you need to set the dataType to 'text' in your .get() options. – T Nguyen Mar 21 '14 at 19:32

1 Answers1

5

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
  }
});
Dmytro Yarmak
  • 1,018
  • 6
  • 6