最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to make window size observable using knockout - Stack Overflow

programmeradmin5浏览0评论

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!

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!

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 badges
Add a ment  | 

2 Answers 2

Reset to default 12

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 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>
发布评论

评论列表(0)

  1. 暂无评论