(I know there are other questions here asking the same thing; I've tried them and they don't apply here)
I have a collection being displayed by a Knockout JS foreach. For each item, the visible binding is set by call a method, based on something external to the item itself. When the externality changes, I need the UI to be redrawn.
A striped down version can be seen in this Fiddle: http://jsfiddle.net/JamesCurran/2us8m/2/
It starts with a list of four folder names, and displays the ones starting with 'S'.
<ul data-bind="foreach: folders">
<li data-bind="text: $data,
visible:$root.ShowFolder($data)"></li>
</ul>
<button data-bind="click:ToA">A Folders</button>
Clicking the button should display the ones starting with 'A' instead.
self.folders = ko.observableArray(['Active', 'Archive', 'Sent', 'Spam']);
self.letter = 'S';
// Behaviours
self.ShowFolder = function (folder)
{
return folder[0] === self.letter;
}
self.ToA = function ()
{
self.letter = 'A';
}
UPDATE:
After Loic showed me how easily this example could be fixed, I reviewed the differences between this example and my actual code. I'm using an empty object as a dictionary to toggle if an item is selected self.Selected()[item.Id] = !self.Selected()[item.Id];
The object being changed is already an observable. I assumed that Knockout didn't realize that the list is dependent on the external observable, but it does. What Knockout was missing was that the observable was in fact changing. So, the solution was simply:
self.Selected()[item.Id] = !self.Selected()[item.Id];
self.Selected.notifySubscribers();
Here's what I came up with:
What you have to understand is that Knockout is only "answering" to data changes in observables. If an observable changes, it will trigger every object that uses it. By making your self.letter an observable. You can simply change it's value and uses it somewhere like self.letter() and it will automagically redraw when needed.
http://jsfiddle.net/2us8m/3/
function WebmailViewModel() {
// Data
var self = this;
self.folders = ko.observableArray(['Active', 'Archive', 'Sent', 'Spam']);
self.letter = ko.observable('S');
// Behaviours
self.ShowFolder = function (folder)
{
return folder[0] === self.letter();
}
self.ToA = function ()
{
self.letter('A');
}
};
ko.applyBindings(new WebmailViewModel());
In case you have complex bindings, like storing an object inside an observable. If you want to modify that object you have multiple possible choices.
self.Selected()[item.Id] = !self.Selected()[item.Id];
You could change it to this by making everything "observables" but if my memory is right, it can become complicated.
self.Selected()[item.Id](!self.Selected()[item.Id]());
I remember I had one similar issue where I had dependency problem where I had to update a country, region, city. I ended up storing it as list inside an observable to prevent update on individual element change. I had something like this.
var path = PathToCity();
path[0] = 'all';
path[1] = 'all';
PathtoCity(path);
By doing this, the change would be atomic and there will be only one update. I haven't played a lot with knockout for a while. I'm not sure but I do believe that the last time I worked with knockout, it was able to "optimize" and prevent to redraw the whole thing. But be careful because if it is not able to guess that you didn't change many thing, it could redraw the whole observable tree (which could end up pretty bad in term of performance)
In your example, we could use the same behaviour with my modified example:
http://jsfiddle.net/2us8m/4/
Related
When my user select one of the object in my observable array, I want to copy it to a "selectedObject". But when I do that, the layout binding on the "SelectedObject" are not updated.
So I've created an update method but I find it very difficult to maintain. is there a better way?
Here is my selected object ui:
<div class="row" data-bind="with: SelectedFlightObject">
<div>select object:</div>
<div data-bind="html: FlightNumber"></div>
</div>
Here is the js that I want to work but doesn't:
//this do not update the layout:
this.OnFlightClick = function (selectObject) {
this.SelectedFlightObject = selectObject;
}.bind(this);
Here is the js that update the ui but find it hard to maintain.
UpdateFlightObject: function (currentObj, newObj) {
currentObj.AirplaneType(newObj.AirplaneType());
currentObj.ArrivingDate(moment(newObj.ArrivingDate()));
currentObj.FlightNumber(newObj.FlightNumber());
currentObj.Duration(newObj.Duration());
currentObj.ArrivalCode(newObj.ArrivalCode());
currentObj.DeparturCode(newObj.DeparturCode());
},
this.OnFlightClick = function (selectObject) {
FlightFactory.UpdateFlightObject(this.SelectedFlightObject, selectObject);
}.bind(this);
Knockout requires you to use their observable wrappers. These wrappers are where the magic happens, once bound, they are what reports changes in values and receive user input back. Your code should look something like this.
Create:
this.SelectedFlightObject = ko.observable(someInitialValueOrNull);
Retrieve:
this.SelectedFlightObject();
Update:
this.SelectedFlightObject(someNewValueOrNull);
You should make your SelectedFlightObject observable so that when it changes your layout is updated.
this.OnFlightClick = function (selectObject) {
this.SelectedFlightObject(selectObject);
}.bind(this);
Your initial SelectedFlightObject would of course need to have some initial values for flight number, etc...
Remember that doing this does not create a new object
I'm currently working on an app whose database schema changes frequently. This rapid change creates a big problem for my front-end Angular code which consumes the backend JSON API (which I don't have much control over) via Restangular; take the following code for example:
<ul>
<li ng-repeat="item in items">
<h2>{{item.label}}</h2>
</li>
</ul>
There will be a lot of template tags like {{item.label}} scattered everywhere in the front-end code, so whenever the property name changes from, say "label" to "item_label", I'll need to remember where those tags are and change all of them. Of course, I could do a project wide search and replace, but that's not really ideal from an DRY stand point and it'll also be a maintenance nightmare.
My question is, does Angular (or Restangular) provide a way to map model property names to custom ones like this in Backbone?
That way, I can just have something like this
{
label: model.item_label
}
then next time when the "item_label" is changed to something else, I can just update it in this configuration object and not worry about all the references in the templates.
Thanks.
The idea with angular is that you can do whatever you want with the model. While this doesn't point you in any specific direction it does give you the opportunity to implement it in your own OO manner. Say you have an app that has a data object called ...Task a model for tasks might look like..
function Task(initJson){
this.name = initJson._name || 'New Task';
this.completed = initJson.is_completed || false;
this.doneDateTime = initJson.datetime || null;
}
Task.prototype = {
save: function(){
//do stuff with this and $http.put/post...
}
create: function(){
//do stuff with this and $http.put/post
}
//....etc
}
All of this might be wrapped up in a factory.
myApp.factory('TaskFactory',function($http){
var Tasks = []; //Or {};
//above constructor function...
//other helper methods...etc
return {
instance: Task,
collection: Tasks,
init: function(){} // get all tasks? run them through the constructor (Task), populate collection
};
})
You could then edit properties on your constructor (one place (for each data type), the only place). Although this isn't ideal if your using things like Restangular or $resource as they not equipped to be a large backing store but they just assume the properties that come across the wire, which for large, changing applications can sometimes be difficult to manage.
I ended up going with Restangular's setResponseExtractor config property based on this FAQ answer.
It looks like this:
Restangular.setResponseExtractor(function(response, operation, what, url) {
var newResponse = response;
angular.forEach(newResponse.items, function(item) {
item.label = item.item_label;
}
return newResponse;
}
I'm really just starting into knockout and so far it is pretty impressive. With that, there is also an issue I am running into.
I'm trying to take a list of binded objects and when on is clicked, I want it take that model and bind it to another view for further editing, no issues there. The problem I run into is that I get an error saying I cannot bind multiple times to the same element. I have read the ko.cleanNode([domElement]) can be used to circumvent it, but that is really meant to be used internally. I have done some searching and people mention you should use with but I don't think that applies to what I want to do.
Is there a way to apply the bindings but then just update the underlying model context?
Simplified jsfiddle example. My js code starts on like 119, above it the ko mapping plugin.
First, use the external resources to add external resources to your fiddle rather than pasting them into your fiddle.
Second, on your problem, the easiest way to do something like this is to have a SelectedItem property in your view model and bind the child view to it. Something like this:
var MyViewModel = function() {
var self = this;
self.MyItems = ko.observableArray();
self.SelectedItem = ko.observable();
}
var MyChildViewModel = function() {
var self = this;
self.SomeProperty = ko.observable();
}
Now populate MyItems with instances of MyChildViewModel and set SelectedItem to whichever item in MyItems you want to have as your child and bind the child view to SelectedItem:
<div id="theChildView" data-bind="with: SelectedItem">
<span data-bind="text: SomeProperty"></span>
</div>
I have the following html that is bound to an object containing id and status. I want to translate status values into a specific color (hence the converter function convertStatus). I can see the converter work on the first binding, but if I change status in the binding list I do not see any UI update nor do I see convertStatus being subsequently called. My other issue is trying to bind the id property of the first span does not seem to work as expected (perhaps it is not possible to set this value via binding...)
HTML:
<span data-win-bind="id: id">person</span>
<span data-win-bind="textContent: status converter.convertStatus"></span>
Javascript (I have tried using to modify the status value):
// persons === WinJS.Binding.List
// updateStatus is a function that is called as a result of status changing in the system
function updateStatus(data) {
persons.forEach(function(value, index, array) {
if(value.id === data.id) {
value.status = data.status;
persons.notifyMutated(index);
}
}, this);
}
I have seen notifyMutated(index) work for values that are not using a converter.
Updating with github project
Public repo for sample (not-working) - this is a really basic app that has a listview with a set of default data and a function that is executed when the item is clicked. The function attempts to randomize one of the bound fields of the item and call notifyMutated(...) on the list to trigger a visual updated. Even with defining the WinJS.Binding.List({ binding: true }); I do not see updates unless I force it via notifyReload(), which produces a reload-flicker on the listview element.
To answer your two questions:
1) Why can't I set id through binding?
This is deliberately prevented. The WinJS binding system uses the ID to track the element that it's binding to (to avoid leaking DOM elements through dangling bindings). As such, it has to be able to control the id for bound templates.
2) Why isn't the converter firing more than once?
The Binding.List will tell the listview about changes in the contents of the list (items added, removed, or moved around) but it's the responsibility of the individual items to notify the listview about changes in their contents.
You need to have a data object that's bindable. There are a couple of options:
Call WinJS.Binding.as on the elements as you add them to the collection
Turn on binding mode on the Binding.List
The latter is probably easier. Basically, when you create your Binding.List, do this:
var list = new WinJS.Binding.List({binding: true});
That way the List will call binding.as on everything in the list, and things should start updating.
I've found that if I doing the following, I will see updates to the UI post-binding:
var list = new WinJS.Binding.List({binding: true});
var item = WinJS.Binding.as({
firstName: "Billy",
lastName: "Bob"
});
list.push(item);
Later in the application, you can change some values like so:
item.firstName = "Bobby";
item.lastName = "Joe";
...and you will see the changes in the UI
Here's a link on MSDN for more information:
MSDN - WinJS.Binding.as
Regarding setting the value of id.
I found that I was able to set the value of the name attribute, for a <button>.
I had been trying to set id, but that wouldn't work.
HTH
optimizeBindingReferences property
Determines whether or not binding should automatically set the ID of an element. This property should be set to true in apps that use Windows Library for JavaScript (WinJS) binding.
WinJS.Binding.optimizeBindingReferences = true;
source: http://msdn.microsoft.com/en-us/library/windows/apps/jj215606.aspx
I'm using a Backbone.js to keep track of the state in a visualization application.
The model has attributes such as:
indicatorX : "income"
indicatorY : "emissions"
indicatorXScale : "lin"
indicatorYScale : "log"
year : 1980
layout : {leftPanel : {[...]}, rightPanel : {[...]}}
1. What is a good way of handling "dependent attributes" in a Backbone.js model?
For example, when changing the indicatorX attribute, I'd also like the model to update the indicatorXScale attribute.
2. How can I handle "lingering" model attributes? Example:
The model contains this:
indicatorX : "income"
indicatorXScale : "log"
If only indicatorX is set on the model, the scale should be set to the default:
model.set( {indicatorX : "emissions"} )
if("indicatorX" in changedAttrs){
indicatorXScale = dataSource[indicatorX].defaultScale
}
What if however the user wants to override the default scale which is "lin" in the case of the "emissions" indicator?
model.set( {indicatorX : "emissions", indicatorXScale : log} )
As the model attribute indicatorXScale already is set to "log", the changed attribute is not recorded. How can I then make sure that the defaultScale is not loaded in this case - but instead the one passed to the model?
3. Is it a good idea to let the model use an extra attribute "action" to describe changes in the model?
In this way controllers can listen for one attribute instead of specifying handlers for combinations of attributes. These are the alternatives:
Alt 1. Controller has handlers for specific attributes:
this.model.bind("change:year", this.render);
this.model.bind("change:layout", this.updateLayout);
Alt 2. Controller has handler for model change and render() figures out what to do:
this.model.bind("change", this.render);
render() {
var changedAttributes = this.model.changedAttributes
if (a,b && c in changedAttributes) x()
if (a,d in changedAttributes) y()
}
Alt 3. Let model describe what a combination of attribute changes signify:
this.model.bind("change:action", this.render);
render() {
var changedAttributes = this.model.changedAttributes
var action = this.model.get("action")
if (action == gui_changeIndicator) x()
if (action == gui_opacity) y()
}
4. Are there any pitfalls to watch out for when using objects as attributes in a Backbone.js model?
Is it for example expensive to perform isEqual on the layout state that I try to keep in my model? Also, when setting the model, objects are passed by reference, so it better be a new object for the comparison to work?
1. What is a good way of handling "dependent attributes" in a Backbone.js model? For example, when changing the indicatorX attribute, I'd also like the model to update the indicatorXScale attribute.
IMHO, extend the model and bind into the change events. For example:
MyModel = Backbone.Model.extend({
initialize: function() {
this.bind('change:width', this.updateArea);
this.bind('change:height', this.updateArea);
this.updateArea();
},
updateArea: function () {
this.area = this.get('width') * this.get('height');
}
});
var model = new MyModel({height: 10, width: 10});
console.log(model.area); //100
model.set({width: 15});
console.log(model.area); //150
This is pretty basic, but change events are called per key and as a whole 'change'.. so you can bind into certain changes and update as necessary. If it's a large model with lots of keys that are updated intermittently this is definitely the way to go. If it's just those two keys.. well.. you could probably just bind to the regular ol' change event once.
2. How can I handle "lingering" model attributes?
Override the set method and add in some of your own code. Example:
MyModel = Backbone.Model.extend({
constructor: function (obj) {
this.touched = {}; //Set before the prototype constructor for anything being set
Backbone.Model.prototype.constructor.call(this, obj);
//set after for only things that the program has updated.
return this;
},
set: function(attributes, options) {
if(attributes.keyIWantToListenFor !== undefined && !this.touched.keyIWantToListenFor) {
console.log("keyIWantToListenFor was set, let's fire off the right methods");
this.touched.keyIWantToListenFor = true;
}
Backbone.Model.prototype.set.call(this, attributes, options);
return this;
}
});
var model = new MyModel({height: 10, width: 10});
model.set({keyIWantToListenFor: 15});
This keeps absolute "has the key been set at all" on the model. It may not be quite specific enough for your needs, but it does work.. so feel free to use and hack away at it.
3. Is it a good idea to let the model use an extra attribute "action" to describe changes in the model?
The way that the Backbone folks have it set up is that, as you already know, change:key is specifically for the change event on a certain key. By relying on a change:action you're kind of adding 'gotcha!'s to your code. I don't see how the other two methods are any better than the first, especially considering now you have logic thrown into an event listener to determine what to fire off.. instead of just attaching that code directly to the appropriate listeners. Given a choice, I'd stick with the first one - it is a clear "This key has updated, so we're going to do X". Not a "something has updated so let's go figure out what it is!" and potentially have to go through a dozen if statements or switches.
4. Are there any pitfalls to watch out for when using objects as attributes in a Backbone.js model?
Well, isEqual performs a deep comparison.. so you're running the risk of doing all of that comparison code plus the risk of recursion. So, yes, that could certainly be a pitfall if you're doing it a number of times.
The object by reference is certainly an issue - I've got a nice little hole in the wall where I've put my head through a few times wondering why something changed in a completely unrelated.. oh wait..
To remedy this a bit, you could override the get method to, in cases where it is returning an object, return something like $.extend(true, {}, this.get(key));
Also, you don't really know what exactly changed in the object based on plain Backbone. So, if you're doing lots of 'stuff' on a change (rebuilding a view, etc), you're potentially going to run into performance issues even if all you did was add another attribute to that object and it isn't used for any of said changes. (i.e. set({layout: layoutObj}) vs set({layoutPageTitle: 'blah'}) which may only update the title.. instead of causing the entire view to reload).
Otherwise, at least in the app that I'm working on, we've had no real issues with objects in backbone. They sync fairly well, and it's certainly better than .get('layout.leftPanel[0]') and having some magical translation to make that work. Just be careful of the reference part.
Hope that helps at least a little!