madcapnmckay / Knockout-UI

A home for rich UI components based on KnockoutJS
265 stars 51 forks source link

Dropdown shows '[object object]' in textbox #3

Closed jwcarroll closed 12 years ago

jwcarroll commented 12 years ago

When combining the dropdown plugin with existing options plugin, if one is bound to an observable array of objects, rather than an array of strings, the "optionsText" is not honoured on the selection.

However, it correctly displays the optionsText in the autocomplete dropdown. Probably minor, I am going to dig in to see if I can narrow it down, but wanted to let you know before I started.

So a binding like this:

<select id="states" data-bind="options: states, optionsText: 'stateCode', value: selectedState, optionsCaption: 'Select a State', dropdown: {}">
</select>

Where each "state" object looks like this:

{stateCode: "Tennessee", anotherProp: "value" }
madcapnmckay commented 12 years ago

Hi Josh,

I have fixed the issue. I have no idea why the template was rending multiple times, but fixing the first issue of the [Object] text in the input seemed to fix both issues.

It was being caused by jquery autocomplete overwriting the value returned from the selectedText dependent observable. I debugged that method and it was working correctly, the text was momentarily displaying correctly and then switching back.

I added a preventDefault to the select event which cancels the event and ensures jquery autocomplete doesn't update the input value and it all worked.

Let me know if you still have issues.

Cheers,

Ian

madcapnmckay commented 12 years ago

Hi Josh,

Just as I sent the message I found out the cause of the multiple template rendering. It was caused by the below method believe it or not. this.selectedCountry was undefined, adding the if solved the issue. I added that if to remove the firebug undefined error, must have solved it inadvertently.

countriesObjectViewModel.selectedCountryName = ko.dependentObservable(function(){ if(this.selectedCountry()) { return this.selectedCountry().name; } return ''; }, countriesObjectViewModel);

Cheers,

Ian

jwcarroll commented 12 years ago

Ian,

Thanks so much for the quick turn around on this one. I had not thought of looking into the jQuery plugin overwriting the value. Anyhow, thanks again for getting the fix in place. I'm looking forward to seeing how you solved the issue.

Reading through your code has been and pretty decent learning experience for me as well :)

-- Josh

madcapnmckay commented 12 years ago

No probs. Always looking for suggestions on improving, I only really got serious about learning js in the last 18 months. I don't think my code can be considered the best from best practice viewpoint, but not the worse either.

If you see something you think is hideous and could be improved, feel free to send me a pull request.