0

I'm trying to re-purpose some example Javascript code in a new Assemble.io project. I have a main.js file that creates a instance' of a Backbone view. The value of the first argument of the view's initialize function is determined in main.js to be a boolean, like this:

new MyView(typeof myFunc != "undefined", anotherVar);

In the original example (wihch I'm running as a virtual host in Apache) this all behaves very understandably. In my new project (which is an Assemble.io site, served via grnt-contrib-connect) if the first argument evaluates to false, what is received by MyView.initialize is an empty object, {}. I see this even if I remove the test, and do this:

new MyView(false, anotherVar);

A value of true (or anything else, like a string, array etc) is passed as expected.

Does this make sense to someone?

toby1kenobi
  • 1,609
  • 1
  • 14
  • 24
  • No it doesn't make sense to me. Maybe you need a little bit more debugging? What is the sourcecode of `MyView`? – gitaarik Apr 13 '15 at 22:03

1 Answers1

2

From the Backbone source:

  var View = Backbone.View = function(options) {
    this.cid = _.uniqueId('view');
    options || (options = {});
    _.extend(this, _.pick(options, viewOptions));
    this._ensureElement();
    this.initialize.apply(this, arguments);
  };

If the first argument to the constructor evaluates to false, its replaced by an empty object before initialize is called.

Edit:

It is kind of strange that reassigning options alters the arguments object, but testing with the following function confirms this:

  function checker (options) {
    console.log(arguments);
    options || (options = {});
    console.log(arguments);
  }
Andrew Larson
  • 483
  • 2
  • 7
  • Regarding your edit: [why does changing an argument variable change the `arguments` “array”?](http://stackoverflow.com/questions/10221009/javascript-why-does-changing-an-argument-variable-change-the-arguments-array). So long as an argument is provided for it, `options` is a getter/setter for `arguments[0]`. – Jonathan Lonowski Apr 13 '15 at 22:17
  • Thanks! I'm trying to understand the [specification](http://www.ecma-international.org/ecma-262/5.1/#sec-10.6) on this, and it's good to have a straightforward explanation. – Andrew Larson Apr 13 '15 at 22:19
  • The getter/setters are defined in step 11.c.ii.2-4. – Jonathan Lonowski Apr 13 '15 at 22:23
  • Note: `options || (options = {});` means the same as `if (!options) options = {};` – Jonathan Lonowski Apr 13 '15 at 22:28
  • Thanks for digging into this, that helps - this at least helps me understand why false is becoming {} I'll have to try to do some more debugging to figure out why (seemingly) the same code produces different results in my two scenarios – toby1kenobi Apr 14 '15 at 07:49