Knockout: Split data binding expressions across multiple attributes

Created on 11 Apr 2016  路  7Comments  路  Source: knockout/knockout

I won't be surprised if this issue has come up before, but just in case...

I've seen plugins that extend the binding syntax to use multiple element attributes. This is so clean looking, that I think it should be incorporated into Knockout proper. For example, let's say I have an <input> element like this:

<input type="text" data-bind="textInput: displayName, event: { focus: $parent.onFocus, blur: $parent.onBlur, keydown: $parent.onKeyDown }, css: { invalid: !isNameValid() }", tabindex="0" readonly />

It would be fantastic if I could break this down into multiple attributes like this:

<input type="text"
    data-bind-textInput="displayName"
    data-bind-focus="$parent.onFocus"
    data-bind-event="blur: $parent.onBlur, keydown: $parent.onKeyDown"
    data-bind-css="invalid: !isNameValid()"
    tabindex="0"
    readonly />

Most helpful comment

I couldn't agree more, why knockout.punches hasn't been integrated into the core at this point is beyond me. It is actually THE reason I went back to knockout instead of angular haha

All 7 comments

Your instinct is right @craxal , this is a duplicate -- though I cannot find it immediately.

An alternative worth planting in your brain is e.g. < input type='text' ko-textInput='displayName' ko-focus='...' />.

I think there's a plugin already for this, a plugin is fairly straightforward (you need a new binding-provider), but in any case this is definitely on the radar so I'll close this.

Thanks for the great report @craxal ! If there's something I missed or overlooked, do not hesitate to comment and we can reopen. :)

Cheers

If you use my Punches plugin, you could then bind like this:

<input type="text"
    textInput="{{displayName}}"
    hasFocus="{{ $parent.onFocus }}"
    event.blur="{{ $parent.onBlur }}"
    event.keydown="{{ $parent.onKeyDown }}"
    css.invalid="{{ !isNameValid() }}"
    tabindex="0"
    readonly />

I'm well aware of the existing plugins, and I think they're fantastic! But that's my point. I think they're so wonderful, that they should be incorporated into the core Knockout binding provider.

I like the {{moustache}} syntax, too. Helps make the binding code more apparent.

I couldn't agree more, why knockout.punches hasn't been integrated into the core at this point is beyond me. It is actually THE reason I went back to knockout instead of angular haha

RN's classBindingProvider is great, too - just to put it out there as an option. Especially when it comes to stepping through bindings.

Following up on this issue. I know @brianmhunt said this was a duplicate, but it hasn't been linked to the appropriate issue yet (not sure which it should be myself). Has there been any discussion about this in the last few months?

Was this page helpful?
0 / 5 - 0 ratings