0
votes

The situation is rather simple. I have a list of objects, and I want to render them in an unordered list, with each list item containing a link. For some reason, the KO binding isn't resolving on the items in my list items. First, here's a fiddle:

http://jsfiddle.net/internetH3ro/z4PBT/

The HTML is rather simple:

<ul data-bind="foreach: vm.MenuItems">
    <li data-bind="css: CssClass">
        <a data-bind="text: LinkText, attr: { href: Href }" />
    </li>
</ul>

And here's the minimal JS:

var ViewModel = (function () {
    function ViewModel(json) {
        var self = this;
        self.vm = ko.mapping.fromJS(json);
    };

    return ViewModel;
})();

var json = {
    MenuItems: [{
        LinkText: "Item 1",
        Href: "http://www.google.com",
        CssClass: "active"
    },{
        LinkText: "Item 2",
        Href: "http://www.yahoo.com",
        CssClass: "inactive"
    },{
        LinkText: "Item 3",
        Href: "http://www.microsoft.com",
        CssClass: "inactive"
    }]
};

var vm = new ViewModel(json);
ko.applyBindings(vm);

The error I get is when it tries to bind to the anchor tag, none of the bindings are resolving.

"Uncaught ReferenceError: Unable to process binding "text: function (){return LinkText }" Message: LinkText is not defined"

I suspected that it had something to do with the binding on the LI element, but I removed that and it still fails, even thought that binding works just fine. I've worked with Knockout before, this shouldn't be all that hard, but I can't quite figure this one out.

1

1 Answers

3
votes

I think I found the issue. Knockout doesn't re-write your

<a data-bind="text: LinkText, attr: { href: Href }" /> 

tag which should be written like

<a data-bind="text: LinkText, attr: { href: Href }"> </a> 

for it to be valid HTML and able to have a text node injected into to it like

<a data-bind="text: LinkText, attr: { href: Href }">
    *the value of LinkText here* 
</a> 

See this Fiddle