Dan Prince
Dan Prince

Reputation: 29989

How do I set an object property within a Backbone model

Right, so I have a number of Backbone models going on, and in one of them I have an object that has a set of keys and values, of which the values are modified by locating the key from a string.

So I started out with code that was built on the below principle, I am quite comfortable with how and why this code will output true:

 var boundData = {
     text: 'value' 
 }
 var key = 'text';
 return (boundData[key] === 'value');

So to set the value of the property, I would do something like:

 boundData[key] = 'new value';

Then I decided to translate all of my existing classes to Backbone models. And the problem that I hit, was that I can no longer change my properties with an equals operator, instead I use the set method provided by Backbone for models. This method takes a string as the first parameter, this string identifies the key for the variable that I am trying to change.

 this.set("boundData[" + settings.name + "]", new OpenCore.boundData(settings));

This does not seem to work, and neither does this:

 this.set("boundData." + settings.name, new OpenCore.boundData(settings));

SOLVED IT. Whilst I was writing out the question, I figured out a way to do it. But thought I would leave it here in case others run into the same problem.

This is a solution, whilst it may not be the best (I'd be interested if someone could get the original way sorted.), but it seems to work.

var boundData = this.get('boundData'); //Create a reference of the object with get().
boundData[settings.name] = new OpenCore.boundData(settings); //Update this reference.
//The change will be reflected in the original instance or you can just:
this.set('boundData', boundData);

Hope this helps someone else out!

Upvotes: 1

Views: 646

Answers (1)

Dan Prince
Dan Prince

Reputation: 29989

This is a solution, whilst it may not be the best (I'd be interested if someone could get the original way sorted.), but it seems to work.

var boundData = this.get('boundData'); //Create a reference of the object with get().
boundData[settings.name] = new OpenCore.boundData(settings); //Update this reference.
//The change will be reflected in the original instance or you can just:
this.set('boundData', boundData);

Hope this helps someone else out!

Upvotes: 2

Related Questions