Amar
Amar

Reputation: 1936

Two way binding in knockoutjs

I just now start using knockoutjs. In below code am just trying to bind DIV's width in two-way.

var ViewModel = function () {
    this.width = ko.observable(7);
};

ko.bindingHandlers.widthBinding = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var div = $(element);
        var value = valueAccessor();
        var Width = ko.utils.unwrapObservable(value);
        div[0].style['width'] = Width + "px";
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var value = valueAccessor();
        var Width = ko.utils.unwrapObservable(value);
        div[0].style['width'] = Width + "px";
    }
};
$("#contentDiv").enableResize();
ko.applyBindings(new ViewModel());

<input data-bind="value: width" />
<div id="contentDiv"  data-bind="widthBinding : width" >

In the above code i have two UI elements, one is Text Input and another one is DIV.And we can able to resize that DIV during run time. If i enter some number in text input means that will apply to DIV's width, that is working fine. At the same time if i resize the DIV during run time means its width should reflect in to the text input. Is there any way to do that?

Upvotes: 3

Views: 4204

Answers (1)

Luffy
Luffy

Reputation: 2337

You can use style binding to change width :

<input data-bind="value:width ,style : { width : width()+'px' }" />

http://jsfiddle.net/gurkavcu/GHgX7/

Upvotes: 3

Related Questions