Friday, October 26, 2012

Aliasing Multiple Properties in Knockout JS Bindings

I recently came across another great use for Knockout JS's "with" statement. Traditionally, with is used to limit the binding context to a child class of the view model. However, I recently realized that it's not just limited to the existing view model - you can specify any object in a using directive, even dynamically generated ones.

Which means it's perfect for emulating c# style "using" directives.

 Let me give a (simplistic) example:

<div data-bind="with: {x: longNameItem.LongName, y: longNameItem2.LongName}">
    <div data-bind="text: x.text"></div>
    <div data-bind="text: x.value"></div>
    <div data-bind="text: y.text"></div>
    <div data-bind="text: y.value"></div>

Additionally, this can help restore sanity when referring to grandparent+ classes:

<div data-bind="with: {parent: $parent, controlRoot: $parents[1], thisForm: $parents[2] }"> </div> 

This allows us to set a readable reference to each level of parent, eliminating $parents[???] mixups.

All this said...

If you are needing to frequently refer to multiple deep children, or frequently refer to great grandparents, you may need to refactor.

No comments :

Post a Comment