patternjavascriptMinor
Planning Poker Using Knockout
Viewed 0 times
pokerplanningknockoutusing
Problem
I am trying to build something similar to planning poker and am very new to Knockout and was wondering if anyone could help me improve on my very crude start?
This is what I have so far:
HTML
Selected Card
CSS
JavaScript/Knockout
http://jsfiddle.net/grahamwalsh/63yeD/
This is what I have so far:
HTML
Selected Card
CSS
.profile { width: 50px; height: 80px; color: #FFF; background: black; border: 1px solid #FFF; float: left; line-height:80px }
.highlight { background: yellow !important; border:1px solid #000; color: black; }JavaScript/Knockout
function Step(number) {
this.active = ko.observable(false);
this.name = ko.observable( number);
}
var model = function () {
var items = ko.observableArray([new Step(1), new Step(2), new Step(3), new Step(5),new Step(8),new Step(13),new Step(20),new Step(40),new Step(100)]);
var selectedItems = ko.computed(function () {
return _.filter(items(), function (item) {
return item.active();
});
})
var clicked = function (item) {
items().forEach(function(item){ item.active(false) });
item.active(!this.active());
};
var save = function () {
alert("sending items \n" + ko.toJSON(selectedItems()));
}
return {
items: items,
selectedItems: selectedItems,
save: save,
clicked: clicked
}
}
ko.applyBindings(model);http://jsfiddle.net/grahamwalsh/63yeD/
Solution
You are using function as definition for model and inside that function you are defined an interface to have access to those properties/methods. In complicated cases you would have inflexible usage between definition and public interface. Better solution would be to create definition for the class like this
and then create an instance of it
because a new operator you will create new JS object and this object will be send as scope for current this content. This is commonly used patterns in order to follow OOJ see link here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
var Model = function () {
var self = this;
self.selectedItems = ko.computed(function () {
return _.filter(items(), function (item) {
return item.active();
});
})
}and then create an instance of it
var model = new Model();because a new operator you will create new JS object and this object will be send as scope for current this content. This is commonly used patterns in order to follow OOJ see link here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
Code Snippets
var Model = function () {
var self = this;
self.selectedItems = ko.computed(function () {
return _.filter(items(), function (item) {
return item.active();
});
})
}var model = new Model();Context
StackExchange Code Review Q#49154, answer score: 2
Revisions (0)
No revisions yet.