14

Working a new project using Knockout, the base documentation didn't seem to explain a case as below. Using the below attr calling; An incorrect href is produced: "api/degrees/function c(){if(0"

<a data-bind="attr: { href: '/api/degrees/' + fieldId }">

Although the following produces the fieldId value correctly

<a data-bind="attr: { href: fieldId }">

Is the only way to successfully combine the base url string and JS object value to use a Knockout computed value?

Thanks in advance for the help.

1 Answer 1

18

Try:

<a data-bind="attr: { href: '/api/degrees/' + fieldId() }">
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, nice quick answer and works! Why would the calling parentheses be required when adding a string and not when using by itself?
I don't have a strong enough background in both KO and javascript to quite explain, but I believe it has to do with how KO parses and executes your expression in javascript. In your first case, you're doing string concatenation, so javascript implicitly calls "toString" on fieldId, which is a function, which returns the contents of the function. In your second example, I believe knockout will attempt to invoke fieldId as a function, inorder to get the value, prior to binding. I am assuming that fieldId is of type ko.observable.
@user1742487: To answer your question, all observables are functions. You normally would have to "call" it to get its value. However within a binding, knockout can read an observable directly so it isn't necessary for you to call it when it's all by itself. But the moment you have a more complex expression (such as the string concatenation there), you must call it so you're concatenating the value stored in the observable, not the observable itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.