Skip to content
Maxime LUCE edited this page Feb 25, 2014 · 1 revision

This module allow creation of better View Model by adding commanding concept.

Definition

Synchronous command
define(["komvvm/commands"], function(commands) {
    var myCommand = new commands.Command({
        canExecute: function() { return myCondition; },
        execute: function() { /* ... */ }
    });
});
Asynchronous command
define(["komvvm/commands"], function(commands) {
    var myAsyncCommand = new commands.AsyncCommand({
        canExecute: function(isExecuting) { return !isExecuting && myCondition; },
        execute: function(complete) { $.ajax(...).always(complete); }
    });
});

Usage

Binding Handler
<button data-bind="command: myCommand"></button>
<button data-bind="command: myAsyncCommand"></button>

You can customize event :

<button data-bind="command: { click: myCommand, dblclick: myAsyncCommand }"></button>
From javascript
myCommand.execute();
myAsyncCommand.execute();

you can pass argument to execute method :

myCommand.execute(myArg);
myAsyncCommand.execute(myArg);

Objects definitions

Command

Constructor Options
execute
  • type: function([$data])
  • required

Function to execute when command execution is allowed. Binding handler pass $data to arguments.

canExecute
  • type: function
  • return type: boolean
  • optional
  • default: function() { return true; }

Allow to customize when Command can be executed.

context
  • type: any
  • optional

Custom context to call callbacks with.

Object Properties
canExecute

type: KnockoutComputed
Get if command can be executed.

Object Methods
execute([$data])

$data: any | optional | argument to pass to execute callback.
returns: void
Execute command if possible.

AsyncCommand

Constructor Options
execute
  • type: function(complete) | function($data, complete)
  • required

Function to execute when command execution is allowed. Call complete argument when execution is complete.
Binding handler pass $data to arguments if callback contains two arguments.

canExecute
  • type: function(isExecuting)
  • isExecuting: boolean | allow one time execution.
  • returns type: boolean
  • optional
  • default: function() { return true; }

Allow to customize when AsyncCommand can be executed.

context
  • type: any
  • optional

Custom context to call callbacks with.

Object Properties
canExecute

type: KnockoutComputed
Get if command can be executed.

isExecuting

type: KnockoutObservable
Get if command is executing.

Object Methods
execute([$data])

$data: any | optional | argument to pass to execute callback.
returns: void
Execute command if possible.