Underscore integration with Knockout

SPA Tools integrate Underscore in Knockout and in any collection in SPATools.Data.

Prerequistes

In order to use Messaging, you must start by include necessaries libraries into your page :
  • KnockoutJS
  • UnderscoreJS
  • SPATools.Core

<script type="text/javascript" src="lib/knockout.js" />
<script type="text/javascript" src="lib/underscore.js" />
<script type="text/javascript" src="lib/spatools.core.js" />

Implementation

Every function from Underscore can be called directly from observableArray. There is two implementation of each method.

The first implementation can be called by using the syntaxt : _{nameOfMethod}. It execute the original underscore method over the collection and return the original result.

The second implementation can be called by using the original name of underscore's methods. It embed the result as a computed observable. So the result is updated every time source collection changed.

The collection is automatically injected in original underscore methods, so when using methods from underscore documentation, just ignore the first argument.

!!Sample
var obsArray = ko.observableArray([
    { firstName: ko.observable("Bob"), lastName: ko.observable("Smith") },
    { firstName: ko.observable("Julia"), lastName: ko.observable("Bread") },
    { firstName: ko.observable("Thomas"), lastName: ko.observable("Johnson") }
]);

var result = obsArray._filter(function(person) { return person.firstName().indexOf("a") !== -1 });
console.log(result);
// { firstName: ko.observable("Julia"), lastName: ko.observable("Bread") }
// { firstName: ko.observable("Thomas"), lastName: ko.observable("Johnson") }

var resultComputed = obsArray.filter(function(person) { return person.firstName().indexOf("a") !== -1 });
console.log(resultComputed);
// ko.computed 
console.log(resultComputed());
// { firstName: ko.observable("Julia"), lastName: ko.observable("Bread") }
// { firstName: ko.observable("Thomas"), lastName: ko.observable("Johnson") }

obsArray.push({ firstName: ko.observable("Brad"), lastName: ko.observable("Willson") });

console.log(result);
// { firstName: ko.observable("Julia"), lastName: ko.observable("Bread") }
// { firstName: ko.observable("Thomas"), lastName: ko.observable("Johnson") }

console.log(resultComputed());
// { firstName: ko.observable("Julia"), lastName: ko.observable("Bread") }
// { firstName: ko.observable("Thomas"), lastName: ko.observable("Johnson") }
// { firstName: ko.observable("Brad"), lastName: ko.observable("Willson") }

More on Underscore

Last edited Dec 20, 2012 at 4:36 PM by SomaticIT, version 2

Comments

No comments yet.