How to make window size observable using knockout
javascript, jquery, knockout.js
Solution
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.
Problem
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!