knockout.js - modify DOM in current item in list (

2019-09-09 04:55发布

问题:

In this example I want to use knockout.js to allow the "Expand" link to be clicked and have its text changed to "Collapse". I also want to set the make the jobDetails section visible. This is a very general question of how to get knockout.js to specifically modify the DOM of the "current" item in a list using a click handler.

<script type="text/html" id="job-template">
    <div class="jobContainer">
        <label data-bind="text: JobTitle"></label> 
        <label data-bind="text: CompanyName"></label>
        <div class="jobDetails">
            <label data-bind="text: City"></label>
            <label data-bind="text: State"></label>
        </di>
    <div>
        <a class="expand" href="#" data-bind="click: ???">Expand</a>        
    </div>
    </div>    
</script>

回答1:

This is very straight forward with KO. Here's a simple way to do it. FYI I had to fix your markup slightly.

<div>
    <div class="jobContainer">
        <label data-bind="text: JobTitle"></label>
        <label data-bind="text: CompanyName"></label>
        <div class="jobDetails" data-bind="visible: expanded">
            <label data-bind="text: City"></label>
            <label data-bind="text: State"></label>
        </div>
    <div>
    <a class="expand" href="#" data-bind="click: toggle, text: linkLabel">Expand</a>        
</div>   


var viewModel = function() {
    this.JobTitle = ko.observable("some job");
    this.CompanyName = ko.observable("some company");
    this.City = ko.observable("some city");
    this.State = ko.observable("some state");

    this.someValue = ko.observable().extend({ defaultIfNull: "some default" });

    this.expanded = ko.observable(false);

    this.linkLabel = ko.computed(function () {
        return this.expanded() ? "collapse" : "expand";
    }, this);      

    this.toggle = function () {
        this.expanded(!this.expanded());
    };
};

http://jsfiddle.net/madcapnmckay/XAzW6/

Hope this helps.