Trying to do something about the browser window:
$(window).width(), $(window).height()
) observable using Knockout?Any Suggestion appreciated!
To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.
An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted. The main advantage of KO is that it updates our UI automatically when the view model changes.
The only way to make them observable is to proxy them into observable properties.
var yourViewModel = {
width: ko.observable(),
height: ko.observable()
};
var $window = $(window);
$window.resize(function () {
yourViewModel.width($window.width());
yourViewModel.height($window.height());
});
I don't really understand your second question. Couldn't you just use css for this?
EDIT
Second question. One possibility would be write a binding handler to do this (untested).
ko.bindingHandlers.center {
init: function (element) {
var $el = $(element);
$el.css({
left: "50%",
position: "absolute",
marginLeft: ($el.width() / 2) + 'px'
});
}
}
The 50% and margin-left is a great way to center things in your scenarios since it automatcially works even if the window is resized. Obviously if the divs themselves resize you need to recalculate the left margin, this could always be bound to a value on the viewmodel. Hope this helps.
To elaborate on Dean's comment of his winsize
custom bindingHandler, this is how it can be used:
JS
ko.bindingHandlers.winsize = {
init: function (element, valueAccessor) {
$(window).resize(function () {
var value = valueAccessor();
value({ width: $(window).width(), height: $(window).height() });
});
}
}
self.windowSize = ko.observable();
HTML
<div data-bind="winsize: windowSize"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With