Knockout.js单击更改(不切换)css类

时间:2014-09-13 11:03:26

标签: javascript jquery html css knockout.js

我试图在knockout.js点击事件中操纵css类,但它无法正常工作。目前我基于$ data.IsSelected元素的值绑定css类(true | false)。我无法获得正确的方法来做我想做的事情 - 我应该使用DOM操作(因为我现在正在尝试做)或者我应该将observableArray元素的值更改为true而不是false,示例然后更新ViewModel,理论上这必须更改css类。 这是JS。

<script>
        function StyleViewModel() {
            var self = this;
            self.pref = ko.observableArray();
            self.img = ko.observableArray(["img/style1.png", "img/style2.png", "img/style3.png", "img/style4.png", "img/style5.png", "img/style6.png"]);
            self.toggle = function (data, event) {
                if (data.IsSelected == true) {  
                    //Here i'm trying to manipulate with DOM directly                 
                    $(event.target).closest("div").removeClass("txt-active").addClass("txt");
                    $(event.target).find("a.button").text("Добавить");
                }
                else {                 
                    $(event.target).removeClass("txt").addClass("txt-active");
                    $(event.target).find("div.txt-active > a.button").text("Добавлено");
                }
            }
            $.getJSON('/api/usersprofiles?userguid=' + $("#MainContent_guid").val(), self.pref);
        }
        $(document).ready(function () {
            ko.applyBindings(new StyleViewModel());
            $("#go").click(function () {
                $("div.test-block").each(function () {
                    var style = $(this).find("h3").text();
                    var option = $(this).find("a").text();
                    var selected;
                    if (option == "Добавить") {
                        selected = false;
                    }
                    else if (option == "Добавлено") {
                        selected = true;
                    }
                    var json = "{'UserGUID':'" + $("#MainContent_guid").val() + "', 'Style':'" + style + "', 'Selected':'" + selected + "'}"
                    $.ajax({
                        type: "POST",
                        dataType: "json",
                        contentType: 'application/json; charset=utf-8',
                        url: "/api/usersprofiles",
                        data: json,
                        success: function () { },
                        error: function (xhr, status, error) {
                            var err = eval("(" + xhr.responseText + ")");
                            alert(err.Message);
                        }
                    });
                });
                setTimeout(function () {
                    window.location.replace("default.aspx");
                }, 3000);
            });
        });
    </script>

这就是显示绑定的HTML:

<input type="hidden" runat="server" id="guid" />
    <div class="container">
        <div class="title">
            <h2>Вкусы</h2>
            <p>Что вам по душе?</p>
        </div>
        <div class="styles" data-bind="foreach: pref">
            <div class="test-block" data-bind="click: $root.toggle">
                <input type="hidden" data-bind="value: $data.Id" />
                <div class="bigshadowtest">
                    <img alt="" src="img/bigshadow.png">
                </div>
                <div data-bind="css: $data.IsSelected == true ? 'txt-active' : 'txt'">
                    <h3 data-bind="text: $data.name"></h3>
                    <a href="#" class="button" data-bind="text: $data.IsSelected == true ? 'Добавлено' : 'Добавить'"></a>
                </div>
                <img alt="" data-bind="attr: { src: $root.img }">
            </div>
        </div>
        <table class="info" style="width: 100%; height: 100%;">
            <tr>
                <td style="text-align: center; vertical-align: middle;">
                    <a href="#" id="go" class="gobtn">Поехали!</a>
                </td>
            </tr>
        </table>
    </div>

P.S。这是另一个问题 - 我无法将observableArray self.img绑定到相应的img元素。

1 个答案:

答案 0 :(得分:0)

使您的可观察数组元素可观察。使用mapping plugin,以便您的isSelected将是一个可观察的并反映它对ui的值更改。

更改你的getJson方法(未经测试的代码)


$.getJSON('/api/usersprofiles?userguid=' + $("#MainContent_guid").val(), function(data) {
    ko.mapping.fromJS(data, self.pref);
});

或者不使用映射插件,你可以创建一个新的pref对象,并将服务器中的数据绑定到循环中,并将它们推入observableArray。这种方式比使用映射插件更可控。

    var oPref = function (data) {
        var self = this;

        self.Id = ko.observable(data.Id);
        self.IsSelected = ko.observable(data.IsSelected);
        self.name = ko.observable(data.name);
        self.imgLink = ko.observable(data.imgLink);

        self.toggle = function () {
            if (self.IsSelected()) self.IsSelected(false);
            else self.IsSelected(true);
        }
    }

        function StyleViewModel() {
            var dataFromServer = [ 
                { Id: 1, IsSelected: false, name: "name1", imgLink: "img/style1.png" },
                { Id: 2, IsSelected: false, name: "name2", imgLink: "img/style2.png" },
                 { Id: 3, IsSelected: false, name: "name3", imgLink: "img/style3.png" }]

            var self = this;

            self.pref = ko.observableArray();

            ko.utils.arrayForEach(dataFromServer, function(item) { self.pref.push(new oPref(item)); });
        }
    $(document).ready(function () {
        ko.applyBindings(new StyleViewModel());
    });

你的html应该如下

<input type="hidden" runat="server" id="guid" />
<div class="container">
    <div class="title">
         <h2>Вкусы</h2>

        <p>Что вам по душе?</p>
    </div>
    <div class="styles" data-bind="foreach: pref">
        <div class="test-block" data-bind="click: toggle">
            <input type="hidden" data-bind="value: Id" />
            <div class="bigshadowtest">
                <img alt="" src="img/bigshadow.png">
            </div>
            <div data-bind="css: { 'txt-active': IsSelected(), 'txt': IsSelected() == false }">
                 <h3 data-bind="text: name"></h3>
 <a href="#" class="button" data-bind="text: (IsSelected() == true ? 'Добавлено' : 'Добавить')"></a>

            </div>
            <img alt="" data-bind="attr: { src: imgLink }">
        </div>
    </div>
    <table class="info" style="width: 100%; height: 100%;">
        <tr>
            <td style="text-align: center; vertical-align: middle;"> <a href="#" id="go" class="gobtn">Поехали!</a>

            </td>
        </tr>
    </table>
</div>