Supun Nakandala
Supun Nakandala

Reputation: 59

element bind in knockoutjs

var scrollheight=$('#scrollbox').attr('scrollHeight'); 

I want to do something like above, without using jquery. I came across that I can use knockoutjs element bind - data-bind="element: scrollbox"

But I am not sure how to do it

Upvotes: 0

Views: 1041

Answers (3)

user341073
user341073

Reputation: 21

Add a custom binding

ko.bindingHandlers.scrollTo = {
    init: function(element, valueAccessor) {
        jQuery(element).show().focus();
        if (jQuery(element).position() != null) {
          jQuery(window).scrollTop(jQuery(element).position().top);
        } 
    }    
};

and use it in HTML:

data-bind="scrollTo: {}

Upvotes: 0

danludwig
danludwig

Reputation: 47375

Afaik, ko does not have its own built-in element binding. I created one that I use in a couple of projects, looks like this:

ko.bindingHandlers.element = {
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var name = ko.utils.unwrapObservable(valueAccessor());
        viewModel[name] = element;
    }
};

However, when binding, I put the viewmodel property name in quotes, something like data-bind="element: 'elementName'". The viewmodel would then look like this:

function MyViewModel() {
    var self = this;
    self.elementName = undefined;
    self.doSomething = function() {
        $(self.elementName).fadeOut();
    };
}

Keep in mind that self.elementName will remain undefined until after ko.applyBindings executes. So you should really only use this in click or other event bindings that execute as functions after the viewmodel is bound.

Upvotes: 0

Darbio
Darbio

Reputation: 11418

I would say that, from reading your comments, KnockOutJS isn't the best candidate in your case for handling ajax on scrolling.

This question handles the window.scroll(...) function and makes an ajax call.

Upvotes: 1

Related Questions