简体   繁体   中英

changing “with” property changes styles

I have html that looks something like this:

<div>
    <table>
        <tr onclick="show();">
            <td class="cell">Click to open</td>
        </tr>
    </table>
</div>
<div style="display:none; position:absolute; left:150px" id="hiddenDiv">
    <table data-bind="with: someProperty">
        <tr onclick="hide();">
            <td class="cell" data-bind="text:message"></td>
        </tr>
    </table>
</div>
<input type="button" value="Color cells" onclick="colorCells()" />

And my JavaScript looks like this:

    function show() {
        vm.someProperty(vm.list[1]);
        $("#hiddenDiv").fadeIn("slow");
    }
    function hide() {
        $("#hiddenDiv").fadeOut("slow");
    }
    function colorCells() {
        $(".cell").css("background-color", "Yellow");
    }

    function ViewModel() {
        this.list = [new SubModel("item 1"), new SubModel("item 2")];
        this.someProperty = ko.observable(this.list[0]);
    }

    function SubModel(msg) {
        this.message = msg;
    }

    var vm = new ViewModel();

    $(function () {    
        ko.applyBindings(vm);
    });

I set up a jsFiddle here .

Now the problem is, when you click the button, all the table cells with class "cell" should have their background color changed. However, if the hidden div isn't visible, then when it is made visible, it's background color is still white. The reason for this seems to be because I'm changing the property that is used in a "with" binding that wraps the hidden cell. It seems when you change the property bound with "with", it resets the style for it's subitems.

(If that makes no sense, do this on the jsFiddle. Click the button, then click the "Click to open" cell. Notice that "item 2" isn't highlighted. Click the button again and it'll be highlighted. Now click the "Click to open" cell again, notice that "item 2" is no longer highlighted. Now remove the line that sets "someProperty" in the show function and repeat the experiment. "item 1" is now highlighted correctly regardless of whether or not it was visible when you click the color cells button)

Is this by design? Is there a way to work around it so that changing a property used by "with" doesn't reset the style?

The correct way to solve this problem, IMHO, would be put the color also as an observable, which can be changed onclick of the button. I have the update jsfiddle here

而不是更改css类,请尝试更改单元格的类,而不是css类“ cell”本身,请参阅是否起作用?

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