0

I'm trying to use customBindings but I have no idea how to achieve this. I heard people saying that DOM manipulation shouldn't be mixed in ViewModel so that's why I'm trying to create CustomBindings.

Here's Jsfiddle http://jsfiddle.net/Y3M6n/2/

Here's my HTML

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<div id="div1" class="row">
    Name <input type="text" data-bind="value: name" />
    Surname <input type="text" data-bind="value: surname" />
</div>

<br/>

<div id="div2" class="row">
     Name: <span data-bind="text:name"> 
     Surname: <span data-bind="text:surname"> 
</div>

<button data-bind="click: submit" >Click</button>

And here's my js code.

function Ctrl() {
    var self = this;
    self.name = ko.observable();
    self.surname = ko.observable();
    self.submit = function() {
        alert('How do I swap the two divs here');
    }
}

ko.applyBindings(new Ctrl());

ko.bindingHandlers.swapDiv = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        var div1 = $('#div1').html();
        var div2 = $('#div2').html();

        $('#div1').replaceWith(div2);
        $('#div2').replaceWith(div1);
     }
};

My intention is that the first div shows inputs and after a user clicks on the button it should show the confirmation div (second div, which will be hided and shown). If it passes the validation then just confirmation div (div2) on top of the inputs (div1) so the user can enter new information right away. It's the business requirement to keep the flow smooth.

toy
  • 11,711
  • 24
  • 93
  • 176

1 Answers1

2

Not sure about your intention, but what if you focus not on the markup but on the view models. For example, define the fields in view model and swap the values, not actual markup. like following: http://jsfiddle.net/tabalinas/Y3M6n/1/

<div id="div1" class="row" data-bind="text: text1">
</div>

<br/>

<div id="div2" class="row" data-bind="text: text2">
</div>

var vm = {
        text1: ko.observable("Div 1"),
        text2: ko.observable("Div 2"),
        submit: function() {
            var temp = vm.text1();
            vm.text1(vm.text2());
            vm.text2(temp);
        }
    };

I doubt that custom bindings should be used for this purpose. It's usually used to create some reusable component or specific event.

If I'm wrong, clarify your intentions, and I'll try to help.

tabalin
  • 2,303
  • 1
  • 15
  • 27
  • Thanks for your reply, I'll update my question. My intention is that I would like to do some calculation and after the calculation is done I'd like to sway the two div2 not just the content inside. – toy Feb 09 '14 at 19:41
  • That's fine. I'm pretty sure you can do it with viewmodel. E.g. use "visible" binding, depending on the field of viewmodel. Probably you also need to use "css" binding to add spec styling for the dialog. http://jsfiddle.net/tabalinas/Y3M6n/3/ – tabalin Feb 09 '14 at 20:38