Is it possible to do a 'with' binding?
christo8989 opened this issue · 2 comments
christo8989 commented
http://knockoutjs.com/documentation/with-binding.html
<h1 data-class="City"> </h1>
<p data-class="With">
Latitude: <span data-class="Lat"> </span>,
Longitude: <span data-class="Lon"> </span>
</p>
<script type="text/javascript">
var vm = {
city: "London",
coords: {
latitude: 51.5001524,
longitude: -0.1262362,
},
};
var bindings = {
City: {
text: vm.city,
},
Coords: {
Lat: {
text: vm.coords.latitude,
},
Lon: {
text: vm.coords.longitude,
},
}
};
bindings.With = { with: bindings.Coords, };
ko.bindingProvider.instance.registerBindings(bindings);
</script>
christo8989 commented
For the time being, I have a hack where I do a foreach
binding but give the array one object.
var bindings = {
Coords: {
foreach: [ vm.coords ],
},
With: function (context, classes) {
var bindings = {
Lat: {
text: context.$data.latitude,
},
Lon: {
text: context.$data.longitude,
},
};
ko.bindingProvider.instance.registerBindings(bindings);
},
};
rniemeyer commented
@christo8989 hey! It is possible to use a with
binding. You would need to bind it against data rather than other bindings. So, something like:
var vm = {
city: "London",
coords: {
latitude: 51.5001524,
longitude: -0.1262362,
},
};
var bindings = {
City: {
text: vm.city,
},
Coords: {
Lat: function() {
return { text: this.latitude };
},
Lon: function() {
return { text: this.longitude };
}
},
With: { with: vm.coords }
};
ko.bindingProvider.instance = new ko.classBindingProvider(bindings);
ko.applyBindings(vm);
The element in that case would bind against data-class="Coords.Lat"
(or Lat
and Lon
could be top-level props).
Here is a sample: https://jsfiddle.net/rniemeyer/t3jxfanm/
Hope that helps!