1

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;
      }
    },
});
3
  • 1
    There's really no way to do that in JavaScript. In the middle of an object initializer block, the object being put together doesn't really exist yet, so there's really nothing to refer to. Commented Oct 2, 2015 at 13:01
  • 1
    Are you sure? initialize is called before and myData has been set before it attempts to initialize namedAttributes. Commented Oct 2, 2015 at 13:15
  • By the time it's possible for something to call initialize, the object is already done. Inside that _.bind() call, which will be made during the process of assembling the larger object you're passing to Backbone, that larger object is still "under construction". Commented Oct 2, 2015 at 13:24

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.