how can i implement multiple custom knockout bindings that can be declared in an object literal?
basically instead of doing this:
<input data-bind="customBinding1:observable1, customBinding2: observable2 }" />
I would like to be able to do this:
<input data-bind="customBinding0: { customBinding1: observable1, customBinding2: observable2 }" />
thanks in advance.
With Knockout, bindings are specified in name/value pairs, where name is the name of the binding, and value is the value that will be retrieved within the binding using valueAccessor().
It sounds like you may be wanting to pass multiple values in to a binding, like your kendo example shows. Although each binding can only have a single value, that value can be anything. This means you can pass in an object literal as the value, and the object can have as many properties as you want. These properties can also be of any type that you want - you'll just need to handle them correctly inside your binding.
Here's a simple example:
View
<div data-bind="myBinding: {setting1: viewModelProperty1,
setting2, viewModelProperty2}"></div>
Binding
ko.bindingHandlers.myBinding = {
init: function(element, valueAccessor) {
var options = valueAccessor() || {};
//this gives you the value of setting1
var setting1 = ko.utils.unwrapObservable(options.setting1);
//if you need to do something just when `setting1` changes,
// add a subscription to the value like so:
if( ko.isObservable(options.setting1) ){
options.setting1.subscribe(function(newValue){
//do something because the setting1 value changed
});
}
}
};
You also have the option of specifying multiple bindings, each with its own value, and referencing the additional bindings and values from within the first one. Knockout's options and optionsText bindings are an example of this approach.
Excellent Resource: http://www.knockmeout.net/2011/07/another-look-at-custom-bindings-for.html
Take some time to study and experiment with the examples at the link above. There's a lot of good information here that covers what you need to do.
Related
When I do a push or pop operation on my observable array, it is reflected in the ui. However other operations on the array won't change anything in the UI. Here's an example of my case:
<ul data-bind="foreach: addresses">
<!-- ko template: {name: 'AddressItemTemplate', data: {address: $data, page: 'update-page'} }-->
<!-- /ko -->
</ul>
I use my template in two different pages and thats the reason I am using the template data like that.
<script type="text/html" id="AddressItemTemplate">
<p data-bind="text: (page == 'update-page') ? 'updating' : 'declined'"</p>
<p data-bind="text: address.title"></p>
</script>
Now on js side, ofc I declared the addresses as an observable array
this.addresses = ko.observableArray([addresObject1, addressObject2, ...])
Somewhere on the page, I edit the address values. To have UI reflecting the changes, I do the following:
//suppose we know that the first address is being edited
var tmp_addresses = addresses();
tmp_addresses[0].title = 'blabla';
addresses(tmp_addresses);
And there it is, in the viewModel, I can see that the content of the addresses has been updated, but not in the UI??
addresses.push(someAddressObject);
or
addresses.pop();
works (updates the UI with the new/removed element). But addresses.splice(0, 1, newAddressObject) does not do anything in the UI again.
What am I missing here? How can push pop work and not the others??
Am I experiencing a bug in knockout framework?
UPDATE
I found out a way to do it, but there's something wrong. I'll come to that but first:
I am well aware that if I use observable objects in the observable array, the changes would be reflected in UI. However that is exactly the thing I want to avoid. It is an overkill.
Observable properties should be required in cases where properties are really exposed to user interaction. For example, if you have a UI for setting each of the fields of an object, then yes, observable property would be the right call.
However in my case, I dont even have a UI for updating the address field. Moreover, I dont need tinkering and constantly watching all the properties of all the addresses. In my case, every now and then an update occurs from the server and that changes only a single field in a single address field.
On another perspective the way I suggest should work. I simply update the whole array at once, not every element individually. It's the exactly the same logic with:
someObservableObject({newObject: withNewFields, ...});
Thats why I dont need my objects as observables. I simply want to re-declare the array and be done with the change. For example, it is advised that if you are going to make lots of pushes into the observable array, dont use array.push(...) multiple times, instead re-declare the larger array on to the observable array variable in a similar way I do it in my question. Otherwise, I am telling knockout to track every single object and every single field in them, which is hardly what I want.
Now, I finally got it working but the way I do suggests that there is a cleaner way to do it.
I found out that, the items in the observable array are somehow tracked and not updated when you re-declare the array with them. For example the code I gave in the question would not work. However the code below works:
var tmp_addresses = addresses();
var tmp_addr = tmp_addresses[0];
var new_addr = {};
Object.keys(tmp_addr).forEach(function(key){
new_addr[key] = tmp_addr[key];
});
new_addr.title = 'Hey this is something new!'
addresses.splice(0, 1, new_addr);
Not satisfied? The code below is going to work as well, because we are re-defining the array:
var newAddressObject1 = {...}, newAddressObject2 = {...};
addresses([newAddressObject1, newAddressObject2]);
But the following would not work!
var tmp_addresses = addresses();
var tmp_addr = tmp_addresses[0];
tmp_addr.title = 'Hey this address wont update';
addresses.splice(0, 1, tmp_addr);
How come? I think knockout adds an internal property to his items in observableArrays and when I try to reinsert one, it will not update.
My problem has now morphed into creating a new object with the same properties of the desired item in the observable array. The way I coded above is simply very dirty-looking. There's gotta be a better way to do that
You are wrongly assigning value to observable title that is the reason why UI not reflecting its changes (2 way binding broken).
Thumb rule is always use () notation while assigning a value to observable (keeps two way binding intact)
viewModel:
var ViewModel = function () {
var self = this;
self.addresses = ko.observableArray([{
'title': ko.observable('one')
}, {
'title': ko.observable('two')
}])
setTimeout(function () {
var tmp_addresses = self.addresses();
tmp_addresses[0].title('blabla'); //assigning data to observable
self.addresses(tmp_addresses);
}, 2000)
};
ko.applyBindings(new ViewModel());
working sample here
PS: Don't get deceived by seeing the value change in viewModel the moment you done assigning using = two binding is broken UI wont reflect VM'S changes .
when you splice up your observableArray UI takes it changes check here
The problem was exactly as #jason9187 pointed out in the comments: The references of the objects in the observable array does not change when I edit a field of them. Therefore, KO would not interpret my array as changed. If the observableArray had contained simple data types, then the way I suggested could work without a problem. However, I have an Object in the array, therefore although I edit the Object, it's reference (pointer) remains the same, and KO thinks that all Objects are the same as before.
In order to achieve what I wanted, we have to solve the deep cloning problem in javascript like in this post.
Now there's a trade-off there, deep cloning is very simple in vanilla if you don't have a circular architecture or functions in your objects. In my case, there's nothing like that. The data comes from a restful API. If anybody in the future gets hold of this problem, they need to deep-clone their 'hard-to-clone' objects.
Here's my solution:
var tmp_addresses = JSON.parse(JSON.stringify(addresses())); //Creates a new array with new references and data
tmp_addresses[0].title = 'my new title';
addresses(tmp_addresses);
Or, if you can create address objects, following will work as well:
var tmp_addresses = addresses();
tmp_addresses[0] = new randomAddressObject();
addresses(tmp_addresses);
Here is a fiddle that I demonstrate both of the methods in a single example
I have a collection, I can do this successfully ('this' is the collection instance):
this.on('change:username', function(model,property,something){
// model is backbone model that changed
// property is the property that changed (username in this case)
// something is some empty mystery object that I can't identify
}
however what I want to do is this:
this.on('change', function(model,property,something){
// model is backbone model that changed
// ***how can I read the properties that changed here?***
// something is some empty mystery object that I can't identify
}
the problem is that in the second case, I can't get the property that changed...maybe that's because it's potentially multiple property changes all at once.
How can I capture that properties that changed in the second case? is this possible?
The only way I know how to do this would be
this.on('change', function(model, something){
// something object is unidentifiable
var changed = model.changed; //hash of changed attributes
}
so my other question is: what is that mystery object "something"? It is just an empty object...?
You have a couple of options you can use in general change events:
Backbone.Model#hasChanged: This will allow you to see if a model attribute has changed in the context of this change event. If so, you can get its new value and apply it to the view (or whatever other context) as needed.
Backbone.Model#changedAttributes: This will allow you to get all changed attributes since the last set() call. When called with no parameters, it is a defensively cloned copy of the changed hash; you can also pass in a hash of parameters and get only what is different about the model relative to that set of key/value pairs.
Backbone.Model#previous: This will allow you to get the previous value of a model attribute during a change event.
Backbone.Model#previousAttributes: This will allow you to get all the previous values of a model during a change event. You could use this to completely undo a change (by calling set with the result of this function) if you wanted to.
By the way, the third parameter of the change:attr event (and the second of change) is an options object, which can be useful if you want to specify custom values that can be read by your event handlers. There are also a number of standard options Backbone will handle specially. See the documentation for Backbone.Model#set for more information on the specific options, and take a look at the Backbone event list to see the callback signatures expected when those events are triggered.
Say I have a backend call which returns a list of objects (and properties), and I use ng-option to stick one of the properties (the name) into the dropdown list, which is using ng-model to attach itself to my model object.
My problem comes in when I need to access other properties of the selected object. ng-option lets me bind objects to that dropdown, which is great. However, if I pull the name out to bind that to my model:
<select ng-model="myModel.name" ng-options="fieldlist.fields.name as fieldlist.fields.name for fieldlist in metrics">
I lose reference to the rest of the object's properties. I need to use another property of the selected object, say fieldlist.fields.location, to perform some other action in an ng-change function. So
Is this possible? Is my Angular naiveté showing too much?
I believe you can do:
ng-model="myModel" ng-options="fieldlist.fields as fieldlist.fields.name for fieldlist in metrics"
Assuming you want myModel to contain all the fields in the selected fieldlist
Per your comment - and this may not be best practice, just my initial thought on how I would do it, you could do something like:
ng-model="selectedItem" ng-change="setSelectedItem()" ng-options="fieldlist.fields.name as fieldlist.fields.name for fieldlist in metrics"
and then in your controller
$scope.setSelectedItem() = function() { $scope.myModel.name = selectedItem.name; };
or remove the ng-change and do
$scope.watch(selectedItem, function() { $scope.myModel.name = $scope.selectedItem.name }
And then you can get whatever property you need from $scope.selectedItem
A little late, but good information i found if anyone could use it. Its still a little odd, but it makes it a little cleaner.
Angular released a ngModelOptions directive which, among other useful things, allows you to define the ngModel as a getter/setter function. Using this, you can remove that pesky ng-change or watch (and possibly a $Digest?). Simply place your update function as the ng-model and set your items that way.
<select ng-model="updatefielset" ng-model-options="{getterSetter:true}" ng-options="fieldlist.fields as fieldlist.fields.name for fieldlist in metrics">
$scope.updatefielset(item) = function()
{
if(angular.isDefined(item)
{
$scope.myModel.A = item.A;
$scope.myModel.B = item.B;
$scope.Val = item;
}
return $scope.Val;
};
https://docs.angularjs.org/api/ng/directive/ngModelOptions
I'm trying to change the view model which is bound to some part of a DOM template (instead of changing the values of the view model) but I just can't figure out how or if it's even possible
Here's the scenario:
Create a new View Model object
Bind it (e.g. applyBindings(myViewModel)
Create another View Model object
Bind the new object to the same part of the DOM so all elements are now bound to the new object.
I want to do the equivalent of changing the value of DataContext of a control in WPF (on which KO's MVVM pattern is based)
The reason for this is that I'm trying to use the same view model for both the representation of the object in a list and the representation of the object in its own view, so I already have a view model for all objects being shown in the list.
There are other workarounds but I think this would be the most elegant way to do it.
There are two way of working with multiple viewmodel. The first way is to do multiple binding like #nathan gonzalez said. You should do binding up your viewmodels. However this complicates things a bit. Therefore difficult to manage.
The second way is to use master viewmodel. I would recommend this.
http://jsfiddle.net/sinanakyazici/e29EZ/10/
<div data-bind="with: mainvm">
<span data-bind="text: prop, click : action"></span>
</div>
var vm = function(value)
{
this.prop = ko.observable(value);
var self = this;
this.action = function() {
console.log("clicked: " + self.prop());
}
}
var master = {
mainvm : ko.observable(null)
}
master.mainvm(new vm('viewmodel 1'));
master.mainvm(new vm('viewmodel 2'));
ko.applyBindings(master);
so ko.applyBindings() should cover this for you. you can pass in a 2nd parameter that tells which top level element to apply the bindings to, like so:
ko.applyBindings(myExistingViewModel, $('#someElementId')[0]);
you may want to clean the elements first though, like this:
ko.cleanNode($('#someElementId')[0]);
this completely removes the bindings and clears the in memory data for that element and its children bindings.
I have got a complex model which is contains a load of ko.observable, ko.observableArray and nested objects which contain even more of these observables.
Now originally I had to make methods within each of the models which in composition make up the larger model to take Json data and then populate its observables. Now I tried the ko.mapping plugin but when I use that doing:
ko.mapping.fromJS(jsonData, {}, existingModel);
Which appears to work for most objects, however I have noticed that when I do this it seems to completely overwrite the object, and as I am using knockout js validation i.e:
this.Name = ko.observable().extend({ required: true });
this.Age = ko.observable().extend({ required: true, digits: true });
Problem is that these validation attributes seem to be removed when using the mapping module, so is there a way to get the mapping plugin to just update the values, rather than tampering with the object schema...
I am more than happy to use a different mechanism other than ko.mapping if there is a better way to apply Json data to the models.
From http://knockoutjs.com/documentation/plugins-mapping.html (section Advanced usage)
Sometimes it may be necessary to have more control over how the mapping is performed. This is accomplished using mapping options. They can be specified during the ko.mapping.fromJS call. In subsequent calls you don’t need to specify them again.
So, for example, you can try something like this:
var self = this;
var mapping = {
update: function(arg) {
var data = arg.data;
return {
Name: data.Name && self.Name(data.Name),
Age: data.Age && self.Age(data.Age)
}
}
};
ko.mapping.fromJS(data, mapping);
I ended up having to stick with my approach although I did manage to reduce a LARGE amount of the code written to populate the existing fields by writing the simple plugin below:
https://github.com/grofit/knockout.mapping.merge
It is very simple and doesn't really do much other than just match up objects with the same name to their existing fields. I was hoping to manage child object creation, so it could populate the entire object tree, but alas I ran out of time.
Hopefully it would at least show a possible solution without having to write lots of verbose code to update a model.
If your needs are modest, you can do this with a simple vanilla JS for loop. This example assumes that you have an existing model called 'myViewModel', and data for a partial refresh called 'jsonData':
for (var prop in jsonData) {
if (myViewModel.hasOwnProperty(prop)) {
myViewModel[prop](jsonData[prop]);
}
}
As it's only updating the value, any additional attributes you've attached to the observables should remain in place.