Monthly Archives: August 2010

IntelliJ IDEA Code Completion for Knockout data-bind attributes

I’m a fan of Knockout. Among other awesome features, it allows you to create custom data bindings right inside your HTML using a data-bind attribute. The value of this attribute is actually a piece of JavaScript code that is executed each time the bindings are evaluated. These bindings can be simple or quite complex. Here is a simple example:

<div data-bind="css: { profitWarning: currentProfit() < 0 }">Profit Information</div>

Unfortunately, if you’re working with IntelliJ IDEA (WebStorm/RubyMine) you won’t get all of its JavaScript magic for the data-bind value because it thinks it’s looking at an HTML attribute string, so no code completion, etc.

But there is a way to fix this. IntelliJ supports something called Language Injection (originally called IntelliLang) to detect code fragments within another language, such as JavaScript code inside an HTML script element. Even better, IntelliJ lets you define your own Language Injections. So let’s create one for the Knockout data-bind attribute. It’s pretty straightforward to do, here are the steps…

  • In your project settings (even though Language Injections are global, they are defined in the project settings) select Language Injections
  • Click New then XML Attribute Injection
  • Then fill it out the dialog as follows (see screenshot below)
    • ID is the language type (JavaScript in our case)
    • Prefix/Suffix are used to make the data-bind string valid JavaScript code
    • Local Name indicates the attribute name where the Language Injection applies.

And now you will get all the IntelliJ goodness you love when editing your Knockout data-bindings like code completion, syntax/error highlighting, docs, and navigation!

You don’t have to stop with Knockout of course. You can also create more complicated injection rules using XPath or IntelliJ internal “Program Structure Interface Patterns,” which allow you map to the language structure itself.

I’ve created a few for other cases as well, which I’d be happy to share in another blog post if there’s enough interest. Just let me know in the comments.

%d bloggers like this: