I'm doing a web game with javaScript and KnockoutJs library.
In my html file I have a array foreach, and the number that this array saves, is the same number of buttons that a I have to draw on the page. Like this:
<strong data-bind = "foreach: cena1.opcoes">
<button data-bind="click: $parent.teste">Opcão</button>
<font color="red"><strong data-bind="text: conteudo"> </strong></font><br>
What I want to know is, how will I know which button the player selected?
I put data like a parameter on my button function, but I don't know how this works. like this:
object.teste = function(data) {
}
You can call the function this way:
<button data-bind="click: function() { $parent.teste($data); }">Opcão</button>
or
<button data-bind="click: function() { $parent.teste($data/* here can be any arguments available in the current binding context */); }">Opcão</button>
Update
By default the first parameter is being passed to the click handler function is the current view model - $data in the current binding context.
For more details and advanced scenarios you can check the Knockout JS documentation.
The click binding passes the current item to the bound function.
var vm = {
items: [1, 2, 3],
click: function(data) {
alert('You clicked: ' + data);
}
};
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="foreach:items">
<button data-bind="click:$parent.click">Click</button>
</div>
Related
I'm currently trying to do the following, unfortunately without any success:
Basically, I have an array of objects, where for every object a button is created dynamically via the ng-repeat directive. When clicking a button, a new object is appended to the mentioned array (data will be sent to the server via api calls, the server will update the list internally and send the new array with the new object appended back to the view).
The same goes for deleting elements from that array.
Here's a little sample code of what I mean:
<span ng-repeat="x in allElements">
<button class="btn btn-primary" id="elementButtons">{{x.id}}</button>
</span>
There will be as many buttons as elements in $scope.allElements.
Then there's also this button, which basically causes the array to be reset to 0 elements:
<button id="clearAllElements" type="button" class="btn btn-danger"
data-toggle="button" ng-click="deleteAllElements()">Clear all</button>
The $scope.deleteAllElements() function calls the api to delete all elements from the server and fetches the new (empty) array from the server assigning it to $scope.allElements.
Now, how can I update the view without having to refresh the whole page such that only the created buttons are reloaded?
Thanks for any answers in advance,
a.j.stu
EDIT:
This is the function that is called when an element is to be added:
$scope.addElement = function(elementName) {
if ($scope.checkElementName(elementName)) {
var data = {"name": elementName.toUpperCase(),
"type": /*retrieve type of element from html element*/}
$http.post("api/addElement/", JSON.stringify(data))
.then(function(response) {
$scope.allElements = response.data; //the api call adds the element in the backend and returns an array with all elements appended the new one. This SHOULD refresh the view of all element buttons, but doesn't.
})
.catch(function(response) {
console.log("something went wrong adding element " + elementName);
})
.then(function(response) {
$('#newElementModal').modal('hide'); //#newElementModal is the modal that pops up when clicking a button to add a new element. here the name and type of the element are set and used in the api call above to add the element. Basically, when the modal hides, the view of all buttons should be refreshed.
});
} else {
console.log("invalid identifier of element.");
}
As far as I've understood, the .then() calls are asynchronous. But, if there are only .then() calls following the api call, this should not be a problem, right?
You should not have to worry about resfreshing the page. If your view is connected to the controller whose $scope is updated by the API calls adding and deleting elements, your view will adapt and display the new content.
For what it's worth, here's a snippet showing how it could work. Minus the API calls that add / delete data.
angular.module('dummyApp', [])
.controller('DummyController', function($scope) {
$scope.allElements = [
{ id : 1, name : "Joe"},
{ id : 2, name : "John"},
{ id : 3, name : "Jane"},
{ id : 4, name : "Alice"},
];
$scope.deleteAllElements = function () {
// deleting elements empties the $scope.allElements array
$scope.allElements.length = 0;
};
$scope.addElement = function () {
var element = {
id : generateId(),
name : 'whatever'
}
// new elements are pushed into the $scope.allElements array
$scope.allElements.push(element);
};
function generateId() {
return Math.floor(Math.random()*1000);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.js"></script>
<div ng-app="dummyApp" ng-controller="DummyController">
<span ng-repeat="x in allElements">
<button class="btn btn-primary" id="elementButtons">{{x.id}}</button>
</span>
<br/><br/>
<button id="clearAllElements" type="button" class="btn btn-danger"
data-toggle="button" ng-click="deleteAllElements()">Clear all</button>
<button id="clearAllElements" type="button" class="btn btn-danger"
data-toggle="button" ng-click="addElement()">Add</button>
</div>
use trackby x.id to update the view without refreshing the whole page
Just assign new response data from your server to $scope.allElements and it will be refreshed without reloading page.
I am trying to complete some basic add and delete functionality using knockout js.
I am using asp mvc, the knockout mappings plugin and returning a simple list of strings as part of my viewModel
Currently I get three items from the server and the functionality I've created allows me to delete each of those items. I can also add an item. But if I try to delete an item i have added in the KO script I cannot delete it.
After completing research and some tests I guess i'm using the observable's incorrectly. I altered my code to pass ko.observable(""), but that has not worked. What am I doing wrong?
values on load
Array[4]0: "test 1"1: "test 2"2: "test 3"length: 4__proto__: Array[0]
values after clicking add
Array[4]0: "test 1"1: "test 2"2: "test 3"3: c()length: 4__proto__: Array[0]
ko script
var vm = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
this.deleteBulletPoint = function (bulletPoint) {
self.BulletPoints.remove(bulletPoint)
}
this.addEmptyBulletPoint = function () {
self.BulletPoints.push(ko.observable(""));
console.log(self.BulletPoints())
}
}
HTML
<div class="col-lg-6 col-md-6 col-sm-12">
<h4>Bullet Points</h4>
<div id="oneLinedescriptions" class="input_fields_wrap">
<!-- ko foreach: BulletPoints -->
<div class="form-group">
<div class="input-group">
<input type="text" data-bind="value: $data" class="form-control">
<span data-bind="click: $parent.deleteBulletPoint" class="input-group-addon btn">-</span>
</div>
</div>
<!-- /ko -->
</div>
<button id="btnAddDescription" data-bind="click: addEmptyBulletPoint" type="button" class="btn btn-default add_field_button col-lg-12 animate-off">Add New Bullet Point</button>
</div>
EDIT
I have removed $parent but the below error was returned
Uncaught ReferenceError: Unable to process binding "foreach: function (){return BulletPoints }"
Message: Unable to process binding "click: function (){return deleteBulletPoint }"
Message: deleteBulletPoint is not defined
In addition to this I have been able to add new empty elements but they are not updated when a user changes the value. is this because the element I am adding is not observable? And if so how do I get round it?
I've added a snippet to ilustrate how you add and remove using an Observable Array with Knockout, the majority of the code is straight from yours so you are in the right track.
Note that when binding to the methods, in this case, there's no need to reference the $parent as you are not using nested scopes. Also, when adding, you just need to pass in plain text, as the observableArray is expecting an object.
If you work with more complex types, when adding you'll need to pass the object itself, and reference its properties from it inside the scope of the iterator, you can read more about it here.
Hope this helps.
var vm = function (data) {
var self = this;
this.BulletPoints = ko.observableArray(["test1", "test2", "test3"]);
this.deleteBulletPoint = function (bulletPoint) {
self.BulletPoints.remove(bulletPoint)
}
this.addEmptyBulletPoint = function () {
const c = self.BulletPoints().length + 1;
self.BulletPoints.push("test "+c);
}
}
ko.applyBindings(vm);
a {
cursor: pointer;
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<h4>Bullet Points <span><a data-bind="click: addEmptyBulletPoint">Add +</a></span></h4>
<div data-bind="foreach: BulletPoints">
<div class="input-group">
<h3 data-bind="text: $data"></h3>
<a data-bind="click: deleteBulletPoint">Delete</a>
</div>
<div>
The problems you're having are related to the way ko.mapping treats arrays of primitive types. By design only properties that are part of an object get mapped to observables so an array of strings will become an observableArray of strings. It will not become an observableArray of observable strings.
In order to add/remove items from an array where the items themselves are observable you'll have to make your BulletPoints array an array of objects having the string as a property within:
data = { BulletPoints: [{value: "test1"}, {value: "test2"}] }
Here's a working example: jsfiddle
I have a main View Model for my screen. It consists of 2 child view models.
One handles the registration section.
One handles the login section.
One handles the menu section (If authenticated and what menu items can appear, as well as the "Welcome "Username" type stuff).
$(document).ready(function () {
// Create the main View Model
var vm = {
loginVm: new LoginViewModel(),
registerVm: new RegisterViewModel(),
layoutVm: new LayoutViewModel()
}
// Get the Reference data
var uri = '/api/Reference/GetTimezones';
$.getJSON({ url: uri, contentType: "application/json" })
.done(function (data) {
vm.registerVm.Timezones(data);
});
// Bind.
ko.applyBindings(vm);
});
Once my Login model's "Login" method completes, I want to set the "IsAthenticated" value within the Menu model, as well as some other user info.
So in my login model, I have a SignIn method.
$.post({ url: uri, contentType: "application/json" }, logindata)
.done(function (data) {
toastr[data.StatusText](data.DisplayMessage, data.Heading);
if (data.StatusText == 'success') {
alert($parent.layoutVm.IsAuthenticated());
}
else {
}
})
.fail(function () {
toastr['error']("An unexpected error has occured and has been logged. Sorry about tbis! We'll resolve it as soon as possible.", "Error");
});
The alert code is my testing. I am hoping to access (and set) the IsAuthenticated property of the layoutVm model. That's one of the child models on my main View model.
However, "$parent" is not defined.
How can I update values in the layoutVm, from my loginVm?
$parent is part of the binding context, which is only available during the evaluation of the data-bind (i.e. to the binding handler).
In your viewmodel structure, you'll have to come up with a way to communicate between models yourself. For example, by passing parent view models, or by passing along shared observables. The problem you're describing can be solved by using data-bind="visible: $root.userVM.IsAuthenticated", like I answered in your previous question.
If you'd like to go with the other approach, here's an example on how to share an observable between viewmodels.
var ChildViewModel = function(sharedObs) {
this.myObs = sharedObs;
this.setObs = function() {
this.myObs(!this.myObs());
}.bind(this);
}
var RootViewModel = function() {
this.myObs = ko.observable(false);
this.vm1 = new ChildViewModel(this.myObs);
this.vm2 = new ChildViewModel(this.myObs);
this.vm3 = new ChildViewModel(this.myObs);
}
ko.applyBindings(new RootViewModel());
div { width: 25%; display: inline-block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="with: vm1">
<h4>vm1</h4>
<p data-bind="text: myObs"></p>
<button data-bind="click: setObs">
flip
</button>
</div>
<div data-bind="with: vm2">
<h4>vm2</h4>
<p data-bind="text: myObs"></p>
<button data-bind="click: setObs">
flip
</button>
</div>
<div data-bind="with: vm3">
<h4>vm3</h4>
<p data-bind="text: myObs"></p>
<button data-bind="click: setObs">
flip
</button>
</div>
Note that each of the child view models also have write permission, so you'll have to be careful to not accidentally update the observable
I'm pretty experienced with Knockout but this is my first time using components so I'm really hoping I'm missing something obvious! I'll try and simplify my use case a little to explain my issue.
I have a HTML and JS file called Index. Index.html has the data-bind for the component and Index.js has the ko.components.register call.
Index.html
<div data-bind="component: { name: CurrentComponent }"></div>
Index.js
var vm = require("SectionViewModel");
var CurrentComponent = ko.observable("section");
ko.components.register("section", {
viewModel: vm.SectionViewModel,
template: "<h3>Loading...</h3>"
});
ko.applyBindings();
I then have another HTML and JS file - Section.html and SectionViewModel.js. As you can see above, SectionViewModel is what I specify as the view model for the component.
Section.html
<div>
<span data-bind="text: Section().Name"></span>
</div>
SectionViewModel.js
var SectionViewModel = (function() {
function SectionViewModel() {
this.Section = ko.observable();
$.get("http://apiurl").done(function (data) {
this.Section(new SectionModel(data.Model)); // my data used by the view model
ko.components.get("dashboard", function() {
component.template[0] = data.View; // my html from the api
});
});
}
return SectionViewModel;
});
exports.SectionViewModel = SectionViewModel;
As part of the constructor in SectionViewModel, I make a call to my API to get all the data needed to populate my view model. This API call also returns the HTML I need to use in my template (which is basically being read from Section.html).
Obviously this constructor isn't called until I've called applyBindings, so when I get into the success handler for my API call, the template on my component is already set to my default text.
What I need to know is, is it possible for me to update this template? I've tried the following in my success handler as shown above:
ko.components.get("section", function(component) {
component.template[0] = dataFromApi.Html;
});
This does indeed replace my default text with the html returned from my API (as seen in debug tools), but this update isn't reflected in the browser.
So, basically after all that, all I'm really asking is, is there a way to update the content of your components template after binding?
I know an option to solve the above you might think of is to require the template, but I've really simplified the above and in it's full implementation, I'm not able to do this, hence why the HTML is returned by the API.
Any help greatly appreciated! I do have a working solution currently, but I really don't like the way I've had to structure the JS code to get it working so a solution to the above would be the ideal.
Thanks.
You can use a template binding inside your componente.
The normal use of the template bindign is like this:
<div data-bind="template: { name: tmplName, data: tmplData }"></div>
You can make both tmplData and tmplName observables, so you can update the bound data, and change the template. The tmplName is the id of an element whose content will be used as template. If you use this syntax you need an element with the required id, so, in your succes handler you can use something like jQuery to create a new element with the appropriate id, and then update the tmplname, so that the template content gets updated.
*THIS WILL NOT WORK:
Another option is to use the template binding in a different way:
<div data-bind="template: { nodes: tmplNodes, data: tmplData }"></div>
In this case you can supply directly the nodes to the template. I.e. make a tmplNodes observable, which is initialized with your <h3>Loading...</h3> element. And then change it to hold the nodes received from the server.
because nodesdoesn't support observables:
nodes — directly pass an array of DOM nodes to use as a template. This should be a non-observable array and note that the elements will be removed from their current parent if they have one. This option is ignored if you have also passed a nonempty value for name.
So you need to use the first option: create a new element, add it to the document DOM with a known id, and use that id as the template name. DEMO:
// Simulate service that return HTML
var dynTemplNumber = 0;
var getHtml = function() {
var deferred = $.Deferred();
var html =
'<div class="c"> \
<h3>Dynamic template ' + dynTemplNumber++ + '</h3> \
Name: <span data-bind="text: name"/> \
</div>';
setTimeout(deferred.resolve, 2000, html);
return deferred.promise();
};
var Vm = function() {
self = this;
self.tmplIdx = 0;
self.tmplName = ko.observable('tmplA');
self.tmplData = ko.observable({ name: 'Helmut', surname: 'Kaufmann'});
self.tmplNames = ko.observableArray(['tmplA','tmplB']);
self.loading = ko.observable(false);
self.createNewTemplate = function() {
// simulate AJAX call to service
self.loading(true);
getHtml().then(function(html) {
var tmplName = 'tmpl' + tmplIdx++;
var $new = $('<div>');
$new.attr('id',tmplName);
$new.html(html);
$('#tmplContainer').append($new);
self.tmplNames.push(tmplName);
self.loading(false);
self.tmplName(tmplName);
});
};
return self;
};
ko.applyBindings(Vm(), byName);
div.container { border: solid 1px black; margin: 20px 0;}
div {padding: 5px; }
.a { background-color: #FEE;}
.b { background-color: #EFE;}
.c { background-color: #EEF;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="byName" class="container">
Select template by name:
<select data-bind="{options: tmplNames, value: tmplName}"></select>
<input type="button" value="Add template"
data-bind="click: createNewTemplate"/>
<span data-bind="visible: loading">Loading new template...</span>
<div data-bind="template: {name: tmplName, data: tmplData}"></div>
</div>
<div id="tmplContainer" style="display:none">
<div id="tmplA">
<div class="a">
<h3>Template A</h3>
<span data-bind="text: name"></span> <span data-bind="text: surname"></span>
</div>
</div>
<div id="tmplB">
<div class="b">
<h3>Template B</h3>
Name: <span data-bind="text: name"/>
</div>
</div>
</div>
component.template[0] = $(data)[0]
I know this is old, but I found it trying to do the same, and the approcah helped me come up with this in my case, the template seems to be an element, not just raw html
I'm trying to get my head around observables in knockout js!
However, I'm facing a problem implementing the remove function on an observable array.
My js is as follow:
$(function () {
var data = [{ name: "name1" }, { name: "name2" }, { name: "name3"}];
var viewModel = {
namesList: ko.observableArray(data),
nameToAdd: ko.observable("name4"),
myCustomAddItem: function () {
this.namesList.push({ name: this.nameToAdd() });
},
myCustomRemove: function () {
console.log("before + " + this.nameToAdd());
this.namesList.remove(this.nameToAdd());
console.log("after + " + this.nameToAdd());
}
};
ko.applyBindings(viewModel);
});
and my html is:
Name To add/remove <input type="text" data-bind="value: nameToAdd, valueUpdate: 'afterkeydown'"/>
<ul data-bind="template: {name: 'listTemp1', foreach :namesList}">
</ul>
<p>
<button data-bind="click: myCustomAddItem">Add Item</button>
<button data-bind="click: myCustomRemove">Remove Item</button>
<script id="listTemp1" type="text/html">
<li data-bind="text:name"> </li>
</script>
</p>
my myCustomAddItem works fine, but not the myCustomRemove. I also have put a console.log before and after the this.namesList.remove(this.nameToAdd()); to see if anything's wrong there, but I cannot see any error in there. When I click the "Remove Item" button, firebug console shows the logs but the item's not removed from the list.
Any help appreciated
The parameter to remove should be a function which returns true or false on whether to remove something.
It works quite similarly to the filter function.
In your case, something like this should work:
myCustomRemove: function () {
console.log("before + " + this.nameToAdd());
var nameToAdd = this.nameToAdd();
this.namesList.remove(function(item) {
//'item' will be one of the items in the array,
//thus we compare the name property of it to the value we want to remove
return item.name == nameToAdd;
});
console.log("after + " + this.nameToAdd());
}
[this should be a comment on Jani answer, but I can't still comment on others post, sorry]
Just a small clarification: technically you can call remove() passing the element to remove, see section "remove and removeAll" on http://knockoutjs.com/documentation/observableArrays.html.
the problem with your code is that the elements in 'data' array are objects (containing a property called 'name'), and you are asking to remove from the array the string "name4" (or whatever 'nameToAdd' contains).
You can be tempted to create a new object to pass to remove, like this:
// old code
//this.namesList.remove(this.nameToAdd());
this.namesList.remove({ name: this.nameToAdd() });
but this still fails, because the way javascript object equality works (see, for example: How to determine equality for two JavaScript objects?).
So, in the end you need to use the function anyway.
In this simple example, you can also convert the 'namesList' array to a simple array of strings, and bind "$data" in the template. see http://jsfiddle.net/saurus/usKwA/.
In a more complex scenario, maybe you can't avoid using objects.
[observableArray].remove(function(item) { return item.[whatever] == [somevalue] ; } );