Trying to do something about the browser window:
- Is it possible to make the window size (
$(window).width(), $(window).height()
) observable using Knockout? - How to keep FUTURE Added Elements in the center of the window? Is there something can be done using the jquery live method or the knockout custom bindings?
Any Suggestion appreciated!
Trying to do something about the browser window:
- Is it possible to make the window size (
$(window).width(), $(window).height()
) observable using Knockout? - How to keep FUTURE Added Elements in the center of the window? Is there something can be done using the jquery live method or the knockout custom bindings?
Any Suggestion appreciated!
Share Improve this question edited Apr 10, 2017 at 18:15 Michael Best 16.7k1 gold badge39 silver badges71 bronze badges asked Jun 1, 2012 at 16:35 DeanDean 1,2913 gold badges15 silver badges23 bronze badges2 Answers
Reset to default 12The 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 ment 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>