Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make window size observable using knockout

Trying to do something about the browser window:

  1. Is it possible to make the window size ($(window).width(), $(window).height()) observable using Knockout?
  2. 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!

like image 274
Dean Avatar asked Jun 01 '12 16:06

Dean


People also ask

How do I set observable value in knockout?

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.

What is Ko observable ()?

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.


2 Answers

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.

like image 193
madcapnmckay Avatar answered Sep 23 '22 16:09

madcapnmckay


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>
like image 37
Ray Avatar answered Sep 23 '22 16:09

Ray