Вопрос

// file one

// how to call the choicesCollection setnextOne in ChoicesModel default function(object)

var ChoicesModel = Backbone.Model.extend({
    defaults: function() { 
      // this.collection ??
      return {
        seq_id: choicesCollection.setnextOne(),
        subject: ""
      };
    },
    initialize: function() {

        console.log(this);

      if (!this.get("seq_id")) {
        this.set({"seq_id": this.defaults().seq_id});
      }
    }
});

// file two

var ChoicesCollection = Backbone.Collection.extend({
    model:ChoicesModel,
    setnextOne: function() {
      if (!this.length) return 0;
      return +this.last().get('seq_id') + 1;
    },
    // sort
    comparator: function(choice) {
      return choice.get('seq_id');
    }
});

// file three

var choicesCollection =  new ChoicesCollection();
Это было полезно?

Решение

Giving some more insight into Manikandan's answer...

If you look at the backbone code you'll see the following (I've removed some bits):

var View = Backbone.View = function(options) {
  options || (options = {});
  _.extend(this, _.pick(options, viewOptions));
};

// List of view options to be merged as properties.
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];

As you can see_.pick is used to white list a sub-set of properties from the options passed in. The View prototype is then extended to bolt on these properties (if they've been passed).

In short, the following properties are automatically thrown onto your view if you pass them as options:

model, collection, el, id, attributes, className

Другие советы

As per the backbone documentation you should access the collection by this.collection once you added model to collection. Or you need to send collection option when you create a model.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top