Knockoutjs: ScrollIntoViewTrigger

I recently struggled with a problem, and although I solved it for me, I’m not sure if there are better solutions there, so I will be grateful for any comments.

Problem. I wanted to create a ScrollIntoView binding. Since scrolling an element in a view requires a DOM-Element, I wrote a custom binding, which I would then like to explicitly launch whenever I was glad. I started with this code:

ko.bindingHandlers.scrollTo = {
    update: function (element, valueAccessor, allBindings) {
        var _value = valueAccessor();
        var _valueUnwrapped = ko.unwrap(_value);
        if (_valueUnwrapped) {
            element.scrollIntoView();
        }
    }

};

Binding:

<div data-bind="scrollTo: goToThis">

And in the ViewModel, I had this observable:

_self.goToThis = ko.observable(false).extend({notify: 'always'});

which I could just call by calling:

_self.goTohis(true);

. . , goTothis() Observable true, , , . , , if, , if goToThis, . !

, custum :

    ko.bindingHandlers.scrollTo = {
        update: function (element, valueAccessor, allBindings) {
            var _value = valueAccessor();
            var _valueUnwrapped = ko.unwrap(_value);
            if (_valueUnwrapped) {
                element.scrollIntoView();
// resets the trigger value to false. Otherwise there will be more and more ViewModels, where the value is true.
                if (ko.isWriteableObservable(_value) && typeof (_valueUnwrapped) === 'boolean') {
                    _value(false);
                }
            }
        }
   };

, .

, , : - - scrollIntoView? , ?

, ? .. , .

J

+4
3

scrollTo :

ko.bindingHandlers.scrollTo = {
    update: function (element, valueAccessor, allBindings) {
        var _value = valueAccessor();
        var _valueUnwrapped = ko.unwrap(_value);
        if (_valueUnwrapped) {
            element.scrollIntoView();
        }
    }
};

goToThis 1 , , , :

<div data-bind="scrollTo: $root.scrolledItem() == $data">

, reset, goToThis .

. http://jsfiddle.net/290ew0nr/1/

+6

scrollintoview , , bindingHandler, , , scrollintoview - .

scrollintoview .

css , scrollintoview, , css class current-item, , , , .

, ko DOM. ko , scrollintoview, .

// do my model logic above
// then fire my after-render callback
setTimeout(function() {
  $('.current-item').scrollintoview({direction: 'y'});
  // I am using a different scrollintoview library: https://github.com/litera/jquery-scrollintoview
}, 0);

BTW, ko http://knockoutjs.com/documentation/template-binding.html#note_4_using_afterrender_afteradd_and_beforeremove

template scrollintoview template afterRender .

2 .

0

- . ViewModel, ( ), , . , DOM HTML- ViewModel.

0

All Articles