Knockout binds unexpectedly to properties of window

358 views
Skip to first unread message

Noel Abrahams

unread,
Sep 10, 2012, 1:07:32 PM9/10/12
to knock...@googlegroups.com
Hi,

I'm not sure if this has been reported before, but I've noticed some strange behaviour with KO.

Basically, if you declare a binding in HTML with the name of a property of the window object then KO binds to that property if that property is missing in the view model.


Here is the fiddle:

Any thoughts?

rpn

unread,
Sep 10, 2012, 1:19:27 PM9/10/12
to knock...@googlegroups.com
Hi Noel-
The bindings are basically evaluated as an object literal with the viewModel/context variables moved to the top level so you can reference them directly.  So, global variables are fair game to bind against.

Noel Abrahams

unread,
Sep 11, 2012, 4:49:59 AM9/11/12
to knock...@googlegroups.com
Hi, RPN,

Thanks for that. 

I'm not sure I understand "the variables are moved to the top level so you can reference them directly".

I don't think I ever want to reference my view model properties from the global context.

That seems to be encouraging bad practise, no?

rpn

unread,
Sep 11, 2012, 10:01:22 PM9/11/12
to knock...@googlegroups.com
Hi Noel-
This only happens when evaluating the binding string from the data-bind attribute.  Knockout uses JavaScript's "with" statement when turning the string into a JavaScript object.  This is why you can just say "text: firstName", rather than something like "text: this.firstName".  So, this is isolated to this parsing operation.

Hope that helps.

Noel Abrahams

unread,
Sep 12, 2012, 6:42:13 AM9/12/12
to knock...@googlegroups.com
Okay, thanks, RPN.

Because KO can write to the bound global variables, in addition to reading from them, it is conceivable to accidentally have something like this:

<input data-bind="value:location" />

I think now the browser will make a GET request for any URL entered into the input, because the input is bound to window.location.

A bit far-fetched, but might be a security issue.

It would be nice to get an exception when attempting to bind on non-existent properties within the view model's scope.
(I believe a local variable can be used instead of "with" - but I've not looked into the KO source so that's just a guess.)

I'm sorry for volunteering stuff without looking too much into the KO source, but I have problems of my own! :D



Reply all
Reply to author
Forward
0 new messages