Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockoutjs single and double click

I want to be able to bind a single and double click event to a span of text. I know I can use

data-bind ="event: { dblclick: doSomething }

for a double click, but I also need the ability to perform a different function on single click. Any suggestions?

like image 275
bdev Avatar asked Jun 13 '12 15:06

bdev


People also ask

What is KnockoutJS used for?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.

What is $root in knockout?

$root. This is the main view model object in the root context, i.e., the topmost parent context. It's usually the object that was passed to ko. applyBindings . It is equivalent to $parents[$parents.

What is applyBindings in knockout?

applyBindings do, The first parameter says what view model object you want to use with the declarative bindings it activates. Optionally, you can pass a second parameter to define which part of the document you want to search for data-bind attributes. For example, ko.

What is knockout language?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.


1 Answers

<div data-bind="singleClick: clicked, event : { dblclick: double }">
    Click Me
</div>

This will filter out the single clicks that are also double clicks.

ko.bindingHandlers.singleClick= {
    init: function(element, valueAccessor) {
        var handler = valueAccessor(),
            delay = 200,
            clickTimeout = false;

        $(element).click(function() {
            if(clickTimeout !== false) {
                clearTimeout(clickTimeout);
                clickTimeout = false;
            } else {        
                clickTimeout = setTimeout(function() {
                    clickTimeout = false;
                    handler();
                }, delay);
            }
        });
    }
};

Here is a demo.

like image 95
madcapnmckay Avatar answered Sep 24 '22 00:09

madcapnmckay