3. Israel JavaScript Conference | 03 – 6325707 | info@e4d.co.il | www.js-il.com |
Stands for Model-View-ViewModel
Not technology specific
Awesome with data binding!
MVVM is, foremost, a separation pattern
4. Israel JavaScript Conference | 03 – 6325707 | info@e4d.co.il | www.js-il.com |
Basically just a JavaScript object
Represents the data
5. Israel JavaScript Conference | 03 – 6325707 | info@e4d.co.il | www.js-il.com |
A user friendly presentation of content
The HTML representation layer
6. Israel JavaScript Conference | 03 – 6325707 | info@e4d.co.il | www.js-il.com |
Contains properties, methods and model
model
Holds the behavior and data for the view
var myViewModel = {
name: ko.observable("Johnny"),
lastName: ko.observable("Tordgeman")
};
14. Israel JavaScript Conference | 03 – 6325707 | info@e4d.co.il | www.js-il.com |
Observables are special JavaScript
objects that can notify subscribers about
changes, and can automatically detect
dependencies.
35. Israel JavaScript Conference | 03 – 6325707 | info@e4d.co.il | www.js-il.com |
<div class="navbar-inner navbar-secondary">
<div class="btn-group" data-
bind="foreach: router.visibleRoutes">
<a data-bind="attr: { href: hash }, css:
{ active: isActive }, html: caption"
class="btn btn-info"></a>
</div>
</div>
For each visible route…
Bind the route link
Check if CSS should be
active
And its html to the
content of the link
37. Israel JavaScript Conference | 03 – 6325707 | info@e4d.co.il | www.js-il.com |
Knockout provides us with three methods for custom post-
processing logic of our template:
afterRender
afterAdd
beforeRemove
39. Israel JavaScript Conference | 03 – 6325707 | info@e4d.co.il | www.js-il.com |
ko.bindingHandlers.yourBindingName = {
init: function (element, valueAccessor,
allBindingsAccessor, viewModel) {
// This will be called when the binding is first
applied to an element
},
update: function (element, valueAccessor,
allBindingsAccessor, viewModel) {
// This will be called once when the binding is
first applied to an element,
// and again whenever the associated observable
changes value.
}
};
40. Israel JavaScript Conference | 03 – 6325707 | info@e4d.co.il | www.js-il.com |
ko.bindingHandlers.fadeVisible = {
init: function (element, valueAccessor, allBindingsAccessor,
viewModel) {
var shouldDisplay = valueAccessor();
$(element).toggle(shouldDisplay);
},
update: function (element, valueAccessor, allBindingsAccessor,
viewModel) {
var shouldDisplay = valueAccessor(),
allBindings = allBindingsAccessor();
shouldDisplay ? $(element).fadeIn() : $(element).fadeOut()
;
}
};
Bound DOM
element
1 Value passed
to the binding
2 All bindings
on same element
3
42. Israel JavaScript Conference | 03 – 6325707 | info@e4d.co.il | www.js-il.com |
While Knockout observables provides
the basic features necessary to support
reading/writing values and notifying
subscribers when that value changes,
you may wish to add your own logic to it.