How to make window size visible using knockout

Trying to do something in a browser window:

  • Is it possible to make the window size ( $(window).width(), $(window).height() ) observable using Knockout?
  • How to save FUTURE Added items in the center of the window? Is there anything I can do with jQuery live or custom knockout bindings ?

Any suggestion appreciated!

+6
source share
1 answer

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 do not understand your second question. Could you just use css for this?

EDIT

Second question. One possibility is to write a binding handler for this (untested).

 ko.bindingHandlers.center { init: function (element) { var $el = $(element); $el.css({ left: "50%", position: "absolute", marginLeft: ($el.width() / 2) + 'px' }); } } 

50% and margin on the left is a great way to focus on your scenarios, as it automatically works even when you resize the window. Obviously, if the dimensions of the divs themselves change, you need to recalculate the left margin, this can always be tied to the value on the viewmodel. Hope this helps.

+10
source

Source: https://habr.com/ru/post/917211/


All Articles