In knockout.js, is it possible to use a dynamic binding value? - javascript

In knockout.js, is it possible to let the right-hand-side of a binding (the value of the binding) be dynamic? For example,
<input data-bind="value: dynamicBinding()"/>
<script type="text/javascript">
var vm = {
dynamicBinding : function() {
return "foo().bar";
},
foo : ko.observable({
bar : ko.observable("hi");
}
};
ko.applyBindings(vm);
</script>
the result should be that the the dynamicBinding function is executed while applying the bindings and the resulting string is used as the binding. The input element should be bound to foo().bar, which is the observable with the value "hi".
If you wonder why I would want this, I am trying to render a dynamic table with knockout, where both the rows and the columns are observableArrays, and I want to allow the column definitions to contain the expression of the binding for that column. I.e., I want to be able to do this:
<table data-bind="foreach: data">
<tr data-bind="foreach: $root.columns">
<td data-bind="text: cellValueBinding()"></td>
</tr>
</table>
<script type="text/javascript">
var vm = {
data: ko.mapping.fromJS([
{title: "Brave New World", author: { name : "Aldous Huxley" },
{title: "1984", author: { name : "George Orwell" },
{title: "Pale Fire", author: { name : "Vladimir Nabokov" }]),
columns: ko.observableArray([
{header: "Title", cellValueBinding: function () { return "$parent.title"; }},
{header: "Author", cellValueBinding: function () { return "$parent.author().name"; }}
])
};
ko.applyBindings(vm);
</script>
As you can see from the example, the column definition knows how to extract the value from the data. The table markup itself is more or less a placeholder. But as far as I can tell, this does not work, due to the way knockout processes the bindings. Are there any other options available?
Thanks.
Solution: I ended up using Ilya's suggestion - I can let cellValueBinding be a function that accepts the row and column as arguments, and returns an observable. This technique is demonstrated in this fiddle.

Use ko.computed for it.
Look on example
JSFiddle
EDIT
In your second example, you can pass $parent value ti the function
<td data-bind="text: cellValueBinding($parent)"></td>
and in model
{header: "Title", cellValueBinding: function (parent) { return parent.title; }},
{header: "Author", cellValueBinding: function (parent) { return parent.author().name; }}
JSFiddle

Related

Why angular scope hold reference?

JS
angular.module('bindExample', []).controller('ExampleController', ['$scope', function($scope) {
$scope.gridFields = {
id: {
width: 50
},
price: {
width: 60
},
};
$scope.allData = {
'one': {
id: '1234qwe',
price: 900
},
'two': {
id: 'asdadw',
price: 1700
},
'three': {
id: '342sdaw',
price: 1200
},
};
$scope.edit = function(row) {
console.log(row);
$scope.buffer = $scope.allData[row];
}
}]);
HTML
<div ng-app="bindExample">
<div ng-controller="ExampleController">
<table>
<tbody>
<tr ng-repeat="(row, data) in allData">
<td ng-repeat="(field, option) in gridFields" ng-bind="data[field]"></td>
<td><button ng-click="edit(row)">edit</button></td>
</tr>
</tbody>
</table>
<div>
<input type='text' ng-model="buffer.id"/>
</div>
<div>
<input type='text' ng-model="buffer.price"/>
</div>
</div>
</div>
After click on edit, values go to $scope.buffer variable from $scope.allData, and the inputs use the buffer as model, but when input is change the values in allData variable changing as well, but i don't want this, this is why is try to pass the values to other...
Problem illustrated here: JSFIDDLE
Any idea?
Use angular.copy()
$scope.buffer = angular.copy($scope.allData[row]);
Javascript will hold reference if assigned data is either function or object or array.
It provides a great benifit to the developer in many ways . but if you wanna to remove reference you have to clone it.
using angular
$scope.buffer = angular.copy($scope.allData[row]);
First things, you're going to get unexpected results in ng-repeat if you use a parent object literal rather than an array (Angular doesnt guarantee that it will iterate through keys in order):
$scope.allData = [ //you're better off using an Array
'one': {
id: '1234qwe',
price: 900
},
'two': {
id: 'asdadw',
price: 1700
},
'three': {
id: '342sdaw',
price: 1200
},
]; //see above
Secondly, the reason this is happening is that Javascript copies everything as a reference unless it is a primitive, so when you do this:
$scope.buffer = $scope.allData[row];
You're actually just storing a pointer to the original object $scope.allData[row] in $scope.buffer.
To do a "deep copy" yo ucan use angular.copy as suggested by #moncefHassein-bey in his answer.

Knockout.js not updating bindings in select field

I have an issue with Knockout.js . What I try to do is filter a select field. I have the following html:
<select data-bind="options: GenreModel, optionsText: 'name', value: $root.selectedGenre"></select>
<ul data-bind="foreach: Model">
<span data-bind="text: $root.selectedGenre.id"></span>
<li data-bind="text: name, visible: genre == $root.selectedGenre.id"></li>
</ul>
And the js:
var ViewModel = function (){
self.selectedGenre = ko.observable();
self.Model = ko.observableArray([{
name: "Test",
genre: "Pop"
}
]);
self.GenreModel = ko.observableArray([
{
name: "Pop",
id: "Pop"
},
{
name: "Alle",
id: "All"
}
]);
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
JSFiddle: http://jsfiddle.net/CeJA7/1/
So my problem is now that the select list does not update the binding on the span inside the ul and I don't know why...
The value binding should update the property selectedGenre whenever the select value changes, shouldn't it?
Any ideas are welcome.
There are a lot of issues in your code:
1) self is not a magical variable like this. It's something people use to cope with variable scoping. Whenever you see self somewhere in a JavaScript function be sure there's a var self = this; somewhere before.
2) KnockoutJS observables are not plain variables. They are functions (selectedGenre = ko.observable()). ko.observable() returns a function. If you read the very first lines of documentation regarding observables you should understand that access to the actual value is encapsulated in this retured function. This is by design and due to limitations in what JavaScript can and cannot do as a language.
3) By definition, in HTML, <ul> elements can only contain <li> elements, not <span> or anything else.
Applying the above fixes leads to this working updated sample:
HTML:
<select data-bind="options: GenreModel, optionsText: 'name', value: selectedGenre"></select>
<span data-bind="text: $root.selectedGenre().id"></span>
<ul data-bind="foreach: Model">
<li data-bind="text: name, visible: genre == $root.selectedGenre().name"></li>
</ul>
JavaScript:
var ViewModel = function (){
var self = this;
self.selectedGenre = ko.observable();
self.Model = ko.observableArray([
{
name: "Test",
genre: "Pop"
}
]);
self.GenreModel = ko.observableArray([
{
name: "Pop",
id: "Pop"
},
{
name: "Alle",
id: "All"
}
]);
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);

Knockout: Select in simpleGrid example

I am using the knockout simple grid found here:
http://knockoutjs.com/examples/grid.html
I want to be able to add a select into the grid, which has a data-bind attribute assigned to an object array in my vm.
So I have added another column from the example:
this.gridViewModel = new ko.simpleGrid.viewModel({
data: this.items,
columns: [
{ headerText: "Item Name", rowText: "name" },
{ headerText: "Sales Count", rowText: "sales" },
{ headerText: "Price", rowText: function (item) { return "$" + item.price.toFixed(2) } },
*{ headerText: "Select", rowText: function (item) { return "<select data-bind=\"options:items, optionsText: 'name', optionsValue: 'name'\"></select>" } }*
],
pageSize: 4
});
And changed the text attribute to html within the control:
<td data-bind=\"*html*: typeof rowText == 'function' ? rowText($parent) : $parent[rowText] \"></td>\
The Selects appear, but not populated with data from my object array.
JSFiddle found here:
http://jsfiddle.net/vwj2p/1/
(I have pasted in the code from the simple grid above as I made a change to the simplegrid code).
{ headerText: "Select", rowText: function (item) { return "<select data-bind=\"options:$root.items, optionsText: 'name', optionsValue: 'name'\"></select>" } }
I'm assuming each item object doesn't have an items property and you're trying to reference the viewModel's items array? If so, change your code to the above.
This still won't work, however. If you look at the html binding documentation, you'll see that it's only going to spit out static html. During the binding process when this is all getting rendered, KO doesn't applyBindings to the generated HTML.
I tried playing around with the code a bit to try and do ko.applyBindingsToDescendants(viewModel, {td element}), where {td element} is a reference to the parent element with the html binding on it, when the items observableArray updated but that didn't seem to do anything.
Bottom line, I don't think you're going to get this to work without doing a lot of plumbing work to the simpleGrid. It is just a simple grid, after all.

knockout object value changes but ui remains the same

I have a drop down list that is bound to a SelectedFormat value. The lists options are populated from external source on load and matches the view models data.Format object base on id.
Take a look at the js fiddle
Can anyone tell me why the model updates but the UI is not updating with the correct Format.Name
Thanks.
HTML:
<div data-bind="text:data.Format.Name"></div>
<select data-bind="
options:Controls,
optionsText: 'Name',
value: data.SelectedFormat"></select>
Model:
var jsonData = {
Id: "abc-123",
Name: "Chicken Cheese",
Format: {
Id: 2,
Name: 'Medium',
Other: 'Bar'
}
};
var self = this;
self = ko.mapping.fromJS(data);
self.SelectedFormat = ko.observable(
//return the first match based on id
$.grep(vm.Controls,function(item){
return item.Id === self.Format.Id();
})[0]
);
//when changed update the actual object that will be sent back to server
self.SelectedFormat.subscribe(function (d) {
this.Format = d;
},self);
In your code, you have Format and SelectedFormat. The former isn't an observable and so can't trigger updates. You have to use SelectedFormat instead.
<div data-bind="text:data.SelectedFormat().Name"></div>
Example: http://jsfiddle.net/QrvJN/9/

Knockout mapping - Uniquely identifying nested objects using keys

The Knockout mapping plugin documentation has a section entitled "Uniquely identifying objects using “keys”". This describes how to update part of an object and then only update that part of the display rather than completely replacing the display of all properties of a partially-modified object. That all works splendidly in their simple example, which I have slightly modified here to make my question more clear. My modifications were to:
Replace the object with a corrected name after a 2 second delay.
Highlight the unchanging part of the display, so you can see that it is actually not replaced when the update happens.
1. Simple object (jsFiddle)
<h1 data-bind="text: name"></h1>
<ul data-bind="foreach: children">
<li><span class="id" data-bind="text: id"></span> <span data-bind="text: name"></span></li>
</ul>
<script>
var data = {
name: 'Scot',
children: [
{id : 1, name : 'Alicw'}
]
};
var mapping = {
children: {
key: function(data) {
console.log(data);
return ko.utils.unwrapObservable(data.id);
}
}
};
var viewModel = ko.mapping.fromJS(data, mapping);
ko.applyBindings(viewModel);
var range = document.createRange();
range.selectNode(document.getElementsByClassName("id")[0]);
window.getSelection().addRange(range);
setTimeout(function () {
var data = {
name: 'Scott',
children: [
{id : 1, name : 'Alice'}
]
};
ko.mapping.fromJS(data, viewModel);
}, 2000);
</script>
But what isn't clear to me is how I would achieve the same behavior for a more complex nested data structure. In the following example, I took the above code and wrapped the data in a list. I would like this to behave the same as above, but it doesn't. The whole display is redone because of the change in one property. You can see this because, unlike the above example, the highlighting is lost after the data is updated.
2. More complex nested object (jsFiddle)
<!-- ko foreach: parents -->
<h1 data-bind="text: name"></h1>
<ul data-bind="foreach: children">
<li><span class="id" data-bind="text: id"></span> <span data-bind="text: name"></span></li>
</ul>
<!-- /ko -->
<script>
var data = {
parents: [
{
name: 'Scot',
children: [
{id : 1, name : 'Alicw'}
]
}
]
};
var mapping = {
children: {
key: function(data) {
console.log(data);
return ko.utils.unwrapObservable(data.id);
}
}
};
var viewModel = ko.mapping.fromJS(data, mapping);
ko.applyBindings(viewModel);
var range = document.createRange();
range.selectNode(document.getElementsByClassName("id")[0]);
window.getSelection().addRange(range);
setTimeout(function () {
var data = {
parents: [
{
name: 'Scott',
children: [
{id : 1, name : 'Alice'}
]
}
]
};
ko.mapping.fromJS(data, viewModel);
}, 2000);
</script>
So basically what I'm asking is, how can I make the second example work like the first, given the more nested data structure? You can assume that ids are unique for each child (so if I added another parent besides Scott, his children would start with id=2, etc.).
Interesting observation there and nice write-up. It appears to work if you define a key on the parent as well as the child. Try this fiddle:
http://jsfiddle.net/8QJe7/6/
It defines instantiable view model functions for the parents and children, where the parent constructor does its child mappings.

Categories

Resources