Sane
Sane

Reputation: 594

Accessing variables from object declaration

this might be a simple question, but I've spent some time with it and I can't figure out what to do.

I've got a Backbone model and I'm trying to pass myData as an argument to MyModels in namedAttributes. Bind doesn't really help, since "this" is the context of namedAttributes, not RS.Models.MyModel.

Any suggestions?

RS.Models.MyModel = Backbone.Model.extend({

    myData: {},

    namedAttributes: {
      "collection": _.bind(function(attrs) {
        // "this" is the wrong context. How do I access myData from here?
        var options = {myData: this.myData};
        return new RS.Models.MyModels(attrs, options)
      }, this)
    },

    initialize: function(attributes, options) {
      if (options && options.columnData) {
        this.myData = options.myData;
      }
    },
});

Upvotes: 1

Views: 37

Answers (1)

nanobar
nanobar

Reputation: 66475

You need to make namedAttributes a function so that it has the correct context (it's evaluated at runtime then). Many of Backbone's properties can also be functions which return values for this reason (e.g. className, attributes etc) - and in case you want to perform logic to decide what the return value will be. Underscore has a function called _.result for this purpose:

RS.Models.MyModel = Backbone.Model.extend({

    myData: {},

    namedAttributes: function() {
      return {
        collection: new RS.Models.MyModels({myData: this.myData})
      };
    },

    initialize: function(attributes, options) {
      if (options && options.columnData) {
        this.myData = options.myData;
      }
    },
});

You would get the value of namedAttributes with _.result(this, 'namedAttributes').

If it's definitely a function and you want to pass attrs to it then this.namedAttributes.call(this, attrs) will do. _.result is for when it can be either an object or a function.

Upvotes: 1

Related Questions