0

I have a custom binding.

<div data-bind="autocomplete : { inputStyle : { marginRight : marginR }}"></div>

in my init function I do this. I add a inputbox that I need to be styled.

$element.append("<input type='text' data-bind='style='" + value.inputStyle + "' />");

I know this wont work, but please can somebody help me do it right.

JotaBe
  • 38,030
  • 8
  • 98
  • 117
user1199595
  • 406
  • 2
  • 7
  • 16

2 Answers2

1

Here is the custom binding doing what you requested:

function toStyleStr (obj) {
    var result = "";
    $.each(obj, function (k,v) {
        result += k.toString() + ": " + ko.utils.unwrapObservable(v).toString() + ";"; 
    });    
    return result;               
}

ko.bindingHandlers.autocomplete = {
    init: function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()),
            $element = $(element);
        $element.append("<input type='text' style='" + toStyleStr(value.inputStyle) + "' />");     
    }            
};

var model = {
    marginR: ko.observable("10px")
};
ko.applyBindings(model);

Here is a working fiddle: http://jsfiddle.net/RYnbR/2/

gbs
  • 3,529
  • 2
  • 20
  • 18
0

Well I don't really understand what you want to do. But some comments:

$element.append("<input type='text' data-bind='style='" + value.inputStyle + "' />

doesn't work. Style binding receives an object with the style and the value: something like

$element.append("<input type='text' data-bind='style:{color:#ff0000}' />");

so you could do

$element.append("<input type='text' data-bind='style:{color:"+value.inputStyle.marginRight +"}'/>");

this assuming marginR has a color as string.

But why data-bind it then ? You could do:

$element.append("<input type='text' style='color:"+value.inputStyle.marginRight +"'/>")
CodeHacker
  • 2,127
  • 1
  • 22
  • 35
  • Yes as I said I understand that my code dosen't work. But the thing I want is to transfer the hole style binding down to my input. So I dont have to sepcify any color or so. – user1199595 Dec 14 '12 at 12:16