简体   繁体   中英

KnockoutJS "click: binding not working

I am trying to create a page that will replace content in a DOM element when another button is click. I am using KnockoutJS to manage binding and click events. I have a method in my ViewModel that will load some text from a text file, and replace the DOM content with the text file content. The issue is that clicks don't seem to be working:

HTML

<!DOCTYPE html>
<html>
    <head>
        <title>About Me</title>
        <link rel="stylesheet" type="text/css" href="css/styles.css">
        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script src="js/knockout-3.3.0.js"></script>
        <script src="js/nav-mobile.js"></script>
        <script src="js/app.js"></script>
    </head>
    <body>
        <!-- nav bar -->
        <nav>
            <ul class="navbar">
                <li><h1 class="title">About Me</h1></li>
                <li class="nav-text" data-bind="click: setPage.bind('fam')"><p>Family</p></li>
                <li class="nav-text" data-bind="click: setPage.bind('mlg')"><p>MLG</p></li>
                <li class="nav-text" data-bind="click: setPage.bind('bio')"><p>Bio</p></li>
                <li class="nav-text" data-bind="click: setPage.bind('int')"><p>Interests</p></li>
            </ul>
        </nav>

        <!-- main section -->
        <section>
            <div class="main">
                <p class="text-main"></p>
            </div>
        </section>
    </body>
</html>

JavaScript

$(document).ready(function() {
    function ViewModel() {
        var self = this;

        self.text = ko.observable();

        self.setPage = function(page) {
            $.get("../res/text/" + page + ".txt", function(data) {
                console.log("Fetching " + page + ".text" );
                $(".text-main").html(data);
            });
        }
    }

    ko.applyBindings(new ViewModel());
});

I was at least hoping to the something logged to the console, but no. The developer tools don't show anything. I have also tried binding like this:

data-bind="click: setPage('fam')"

but it does not work. What is wrong with my click binding?

The correct syntax for using .bind is .bind($data, 'parameter')

<li class="nav-text" data-bind="click: setPage.bind($data, 'fam')"><p>Family</p></li>
<li class="nav-text" data-bind="click: setPage.bind($data, 'mlg')"><p>MLG</p></li>
<li class="nav-text" data-bind="click: setPage.bind($data, 'bio')"><p>Bio</p></li>
<li class="nav-text" data-bind="click: setPage.bind($data, 'int')"><p>Interests</p></li>

JsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM