4

Is there a shorthand way to create an object with a property field variable?

Say I have the variable PROP.Todo.PRIORITY = 'priority' and then, using Backbone in this example, I want to save this property, how can I avoid having to create a new object, assigning it to some variable and then set the property?

I want to achieve this:

var tmpObj = {};
tmpObj[PROP.Todo.PRIORITY] = "high";
this.model.save(tmpObj);

I've tried something like this, which was unsuccessful:

this.model.save(({}[PROP.Todo.PRIORITY] = "high"));

Any suggestions? I'm going to be writing a lot of long-hand object declarations otherwise.

Ed .
  • 6,373
  • 8
  • 62
  • 82

2 Answers2

4

If you save only one parameter, Model.save has a an alternative way of receiving arguments, (key,value,options)

http://backbonejs.org/#Model-save

save model.save([attributes], [options])
[...] As with set, you may pass individual keys and values instead of a hash. [...]

which means you could write your example as

this.model.save(PROP.Todo.PRIORITY, "high");

If you want to save multiple properties simultaneously, you will have to write a temporary object.

nikoshr
  • 32,926
  • 33
  • 91
  • 105
  • +1 for reading the docs. :) Didn't realize there was a way to do that. – casablanca Jul 04 '12 at 10:09
  • Thanks - this is what I'll go with. However I think I'm going to accept the other answer seeing as in future, if people arrive here via Google, it more directly answers the title of the question..hope you understand! – Ed . Jul 04 '12 at 11:33
  • Worth noting; I was using the [TODO MVC webapp](http://addyosmani.github.com/todomvc/) and it uses Backbone `0.5.0-pre` which doesn't support the suggested way of saving attributes. The latest version (`0.9.2` at time of writing) does however. – Ed . Jul 04 '12 at 12:22
  • @Ed. Good catch, I had forgotten that this syntax came with 0.9.0 – nikoshr Jul 04 '12 at 12:27
2

If you just want an easier way to create the object, how about using a helper function?

function obj(prop, value) {
  var o = {};
  o[prop] = value;
  return o;
}

this.model.save(obj(PROP.Todo.PRIORITY, "high"));

I'm not sure I understand the latter part of your question:

I'm going to be creating a lot of temporary objects otherwise.

You'll have to create an object in any case, and I doubt creating objects is a performance issue.

casablanca
  • 69,683
  • 7
  • 133
  • 150
  • Thanks for the answer - I like this solution, although the other answer will probably be my route of choice. And yes, my wording could have been better; I don't mean 'temporary', what I meant was a lot of declaring of new objects would be required...i.e. lots of code bloat, it wasn't a concern over performance. – Ed . Jul 04 '12 at 11:25