How to Clone Models in Backbone - javascript

I have a model which can be edited by a certain view; however, at the bottom of the view the user should get an option to save or discard all changes. This means that you will need to store a list of all the changes to be made to the model and then make those changes only once the 'save' button has been clicked. This sounds unnecessarily complicated and I have come up with an idea of an alternative approach which is to create a clone of the model and make changes to that in the view. Then if the user clicks 'save' delete the old model and replace it in its collection with the new one, otherwise you discard the cloned model.
This this an acceptable approach, and if so, how can I implement the cloning process?
This would be equivalent to fetching the data from the server again (but an extra HTTP request seems unnecessary).

You could use the clone method. Short example below:
var Model = Backbone.Model.extend({});
var View = Backbone.View.extend({
initialize: function() {
this.realModel = this.model;
this.model = this.realModel.clone();
},
onSave: function() {
this.realModel.set(this.model.attributes);
}
});
You could also do something a bit different:
var Model = Backbone.Model.extend({});
var View = Backbone.View.extend({
initialize: function() {
// save the attributes up front, removing references
this._modelAttributes = _.extend({}, this.model.attributes);
},
onSave: function() {
// revert to initial state.
this.model.set(this._modelAttributes);
}
});

You can give Backbone.Memento a try.
If you don't want to use it no problem. But, You can get a good idea about how it should be done from the codebase.

I usually solve this issue with an object cache on the view. That way I don't add any unnecessary overhead to model/view management. Discarding happens naturally if the user closes out of a view without saving.
var Model = Backbone.Model.extend({
'title': 'Hello'
});
var View = Backbone.View.extend({
initialize: function() {
// Holds temporary values until save
this.cache = {};
},
onTitle: function() {
this.cache.title = 'World';
},
onSave: function() {
this.model.set( this.cache );
}
});

Related

When to destroy my model in case of multiple views depending on it

I have a case where I am creating multiple views for a single model. When I close a view, I am removing the model from the collection.
But in case of multiple views, there are other views that depend on the model.
So, how can I know when there are no views depending on the model? When should I destroy the model in case of multiple views?
Generally speaking the lifecycle of a view shouldn't cause a model/collection to be modified, but assuming you have a good reason for it.
Here is a slight improvement on Kenny's answer, I'd suggest to have dependentViews as an array on the object, not a value in the attributes (if Views aren't persisted, best not persist view dependencies).
var myModel = Backbone.Model.extend({
initialize: function() {
this.dependentViews = [];
},
addDependentView: function(view) {
this.dependentView.push(view);
},
closeDependentView: function(view) {
this.dependentViews = _.without(this.dependentViews, view);
if (_.isEmpty(this.dependentViews)) {
//remove model from collection
}
}
})
var view1 = Backbone.View.extend({
initialize: function() {
this.model.addDependentView(this);
}
})
var view2 = Backbone.View.extend({
initialize: function() {
this.model.addDependentView(this);
}
})
...
onCloseView: function() {
this.model.closeDependentView(this);
}
Also an array of objects might come in handy for the dependency list, that way you could if necessary in future, make calls from the model to the dependent views.
Another possible solution might be to use the internal event listener register as a means of tracking any objects listening to the model. But that would be more involved and would depend on internal functionality within Backbone.
Though this is not a proper way but still you can achieve this following
Declare dependentViews in your model's defaults
var myModel = Backbone.Model.extend({
defaults: function() {
return {
dependentViews: 0
};
}
});
In initialization of each view, increment the dependentView
var view1 = Backbone.View.extend({
initialize: function() {
this.model.set("dependentViews",
this.model.get("dependentViews") + 1);
}
});
var view2 = Backbone.View.extend({
initialize: function() {
this.model.set("dependentViews",
this.model.get("dependentViews") + 1);
}
});
On close of view decrement dependentViews and on each view destroy, just check the value of dependentViews. If it is 0, remove the model from the collection.
onCloseView: function() {
this.model.set("dependentViews",
this.model.get("dependentViews") - 1);
if (this.model.get("dependentViews") === 0) {
//remove model from collection
}
}
Having the number of views inside the data model as suggested in other answers is not a good idea.
I have a case where I am creating multiple views for a single model
So you have a "place" where you create views, and destroy these views. This could be a parent view, controller, router instance etc.
If you don't have one then you need one.
You must be having references to these view instances for future clean up.
If you don't have it then you need it.
When you're destroying a view just check the remaining number of instance, if there are none then remove the model (If the view removes itself in response to some user action then it needs to notify the parent of removal).
This is something that should take place outside the view instances and model.

how to render a collection using backbone?

I have this backbone that is working fine, i just want to render the collection is been fetched!
code:
var SearchView = Backbone.View.extend({
events: {
"keyup": "handleChange"
},
initialize: function(){
this.collection.bind("reset", this.updateView, this);
},
render: function(){
// this is where i need help
this.$el.next('#suggestions').append(// iterate over this.collection and apppend here) //
},
handleChange: function(){
var term = this.$el.val();
this.collection.search(term);
},
updateView: function() {
this.render();
}
});
I just want to iterate over this.collection and display the "text" attribute thats inside each collection and append it to the ('#suggestions') el. thanks
Focusing on your reset, render over collections issue, this is how I would do it. This way assumes that when you create your view, the $el is already present and you're passing it in through the View constructor so it's ready to go.
var SearchView = Backbone.View.extend({
template: _.template('<span><%= term %></span>');
initialize: function(){
this.collection.bind("reset", this.render, this);
},
render: function(){
this.addAllTerms();
return this;
},
addAllTerms: function() {
var self = this;
this.collection.each(function(model) {
self.addTerm(model);
});
},
addTerm: function(someModel) {
this.$el.next('#suggestions').append(this.template(someModel.toJSON()));
}
});
It's a bit different from your approach in a few ways. First, we utilize Underscore's template function. This could be anything from span to li to div whatever. We use the <%= %> to indicate that we're going to interpolate some value (which will come from our model.term attribute).
Instead of going to the handler then render, I just bind the collection to render.
The render() assumes we're always going to refresh the whole thing, build from scratch. addAllTerms() simply cycles through the collection. You can use forEach() or just each() which is the same thing except forEach() is 3 characters too long for my lazy bum. ;-)
Finally, the addTerm() function takes a model and uses it for the value that it will append to the #suggestions. Basically, we're saying "append the template with interpolated value". We defined the template function up above as this View object property to clearly separate the template from data. Although you could have skipped this part and just append('<span>' + someModel.get('term') + '</span>') or what not. The _.template() uses our template, and also takes any sort of object with the property that lines up with the one in our template. In this case, 'term'.
It's just a different way to do what you're doing. I think this code is a little more manageable. For example, maybe you want to add a new term without refreshing the whole collection. The addTerm() function can stand on its own.
EDIT:
Not that important but something I utilize with templates that I found useful and I didn't see it when I first started out. When you're passing the model.toJSON() into the template function, we're essentially passing all the model attributes in. So if the model is like this:
defaults: {
term: 'someTerm',
timestamp: '12345'
}
In our previous example, the attribute timestamp is also passed in. It isn't used, only <%= term %> is used. But we could easily interpolate it as well by adding it to the template. What I want to get at is that you don't have to limit yourself to data from one model. A complex template might have data from several models.
I don't know if it's the best way, but what I do is have something like this:
makeHash: function() {
var hash = {};
hash.term = this.model.get('term');
hash.category = anotherModel.get('category');
var date = new Date();
hash.dateAccessed = date.getTime();
return hash;
}
So you can easily build your own custom hash to throw into a template, aggregating all the data you want to interpolate into a single object to be passed into a template.
// Instead of .toJSON() we just pass in the `makeHash()` function that returns
// a customized data object
this.$el.next('#suggestions').append(this.template(this.makeHash()));
You can also easily pass in whole objects.
makeHash: function() {
var hash = {};
hash.term = this.model.get('term');
var animal = {
name: 'aardvark',
numLegs: 4
};
hash.animal = animal;
return hash;
}
And pass this into our template that looks like this:
template: _.template('<span><%= term %></span>
<span><%= animal.name %></span>
<span><%= animal.numLegs %></span>')
I'm not sure if this is the best way but it helped me understand exactly what data is going into my templates. Maybe obvious but it wasn't for me when I was starting out.
I found the solution to the problem, im gonna put it here for people that might want to know:
render: function(){
this.collection.forEach(function(item){
alert(item.get("text"));
});
}

Backbone JS: can one view trigger updates in other views?

In my simple project I have 2 views - a line item view (Brand) and App. I have attached function that allows selecting multiple items:
var BrandView = Backbone.View.extend({
...some code...
toggle_select: function() {
this.model.selected = !this.model.selected;
if(this.model.selected) $(this.el).addClass('selected');
else $(this.el).removeClass('selected');
return this;
}
});
var AppView = Backbone.View.extend({
...some code...
delete_selected: function() {
_.each(Brands.selected(), function(model){
model.delete_selected();
});
return false;
},
});
Thing is, I want to know how many items are selected. In this setup selecting is NOT affecting the model and thus not firing any events. And from MVC concept I understand that views should not be directly talking to other views. So how can AppView know that something is being selected in BrandViews?
And more specifically, I AppView to know how many items were selected, so if more than 1 is selected, I show a menu for multiple selection.
You might want to have a read of this discussion of Backbone pub/sub events:
http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js/
I like to add it in as a global event mechanism:
Backbone.pubSub = _.extend({}, Backbone.Events);
Then in one view you can trigger an event:
Backbone.pubSub.trigger('my-event', payload);
And in another you can listen:
Backbone.pubSub.on('my-event', this.onMyEvent, this);
I use what Addy Osmani calls the mediator pattern http://addyosmani.com/largescalejavascript/#mediatorpattern. The whole article is well worth a read.
Basically it is an event manager that allows you to subscribe to and publish events. So your AppView would subscript to an event, i.e. 'selected'. Then the BrandView would publish the 'selected' event.
The reason I like this is it allows you to send events between views, without the views being directly bound together.
For Example
var mediator = new Mediator(); //LOOK AT THE LINK FOR IMPLEMENTATION
var BrandView = Backbone.View.extend({
toggle_select: function() {
...
mediator.publish('selected', any, data, you, want);
return this;
}
});
var AppView = Backbone.View.extend({
initialize: function() {
mediator.subscribe('selected', this.delete_selected)
},
delete_selected: function(any, data, you, want) {
... do something ...
},
});
This way your app view doesn't care if it is a BrandView or FooView that publishes the 'selected' event, only that the event occured. As a result, I find it a maintainable way to manage events between parts of you application, not just views.
If you read further about the 'Facade', you can create a nice permissions structure. This would allow you to say only an 'AppView' can subscribe to my 'selected' event. I find this helpful as it makes it very clear where the events are being used.
Ignoring the problems with this that you already mention in your post, you can bind and trigger events to/from the global Backbone.Event object, which will allow anything to talk to anything else. Definitely not the best solution, and if you have views chatting with one another then you should consider refactoring that. But there ya go! Hope this helps.
Here is my case with a similar need: Backbone listenTo seemed like a solution to redirect to login page for timed out or not authenticated requests.
I added event handler to my router and made it listen to the global event such as:
Backbone.Router.extend({
onNotAuthenticated:function(errMsg){
var redirectView = new LoginView();
redirectView.displayMessage(errMsg);
this.loadView(redirectView);
},
initialize:function(){
this.listenTo(Backbone,'auth:not-authenticated',this.onNotAuthenticated);
},
.....
});
and in my jquery ajax error handler:
$(document).ajaxError(
function(event, jqxhr, settings, thrownError){
.......
if(httpErrorHeaderValue==="some-value"){
Backbone.trigger("auth:not-authenticated",errMsg);
}
});
You can use Backbone object as the event bus.
This approach is somewhat cleaner but still relies on Global Backbone object though
var view1 = Backbone.View.extend({
_onEvent : function(){
Backbone.trigger('customEvent');
}
});
var view2 = Backbone.View.extend({
initialize : function(){
Backbone.on('customEvent', this._onCustomEvent, this);
},
_onCustomEvent : function(){
// react to document edit.
}
});
Use the same model objects. AppView could be initialized with a collection, and BrandView initialized with one model from that collection. When attributes of a branch object change, any other code that has a reference to that model can read it.
So lets so you have some brands that you fetch via a collection:
var brands = new Brands([]);
brands.fetch();
Now you make an AppView, and an array of BrandView's for each model.
var appView = new AppView({brands: brands});
var brandViews = brands.map(function(brand) {
return new BrandView({brand: brand});
});
The appView and the brandViews now both have access to the same model objects, so when you change one:
brands.get(0).selected = true;
Then it changes when accessed by the views that reference it as well.
console.log(appView.brands.get(0).selected); // true
console.log(brandViews[0].brand.selected) // true
Same as John has suggested above, the Mediator Pattern works really good in this scenario, as Addy Osmani summing this issue up again in Backbone fundamentals.
Wound up using the Backbone.Mediator plugin which is simple and great, and makes my AMD View modules working together seamlessly =)

How should I attach my data to my Backbone Views?

I have my views correctly displaying fake information and so I am now trying to apply asynchronus data loading to retrieve actual data. The problem is that I am uncertain about how I should go about this. Should I create AJAX calls myself? Should I use the Socket API? Should I use the built in REST api (and how to do so asynchronously)? The server side handler is still unimplemented so as far as how the server serves up the data, that is completely flexible.
i doubt your own ajax calls is what is needed here...
i can't tell about sockets however i know it is possible and a solid idea depending on your app.
i have been using the default REST functionality and it works well for me,
a small example as how I would do it,
to make it less complex i will just act as if it is from page load, instead of using routers and all.
var myView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
var v = this;
this.model.bind("change", function(e) {
this.render();
});
},
render: function() {
this.el.empty();
this.el.text(this.model.get('name'));
}
});
var myModel = Backbone.Model.extend({
url: "/api/myModel", // change to your server code...
defaults: {
name: "john"
}
});
$(function(){
var m = new myModel({}); // dummy model
var v = new myView({ model: m, el: $('#myDiv')});
v.render();
m.fetch(); // takes the url of the model or collection and fetches it from the server side ...
});
if you want to test what the fetch would do, you can for try this code from your console, (or add it to the jquery document load function:
m.set({ name: 'peter' });
this changes the model's property 'name' and you will immediately see the view update itself, because it listens to the change event of the model.
more info on these events can be found here: http://documentcloud.github.com/backbone/#Events

Late JSON Response with Backbone.js

I am working on my first project using backbone.js. It should be a frontend to a Play! App with a JSON interface. Here's a part of my JS code
var api = 'http://localhost:9001/api'
// Models
var Node = Backbone.Model.extend();
// Collections
var Nodes = Backbone.Collection.extend({
model: Nodes,
url: api + '/nodes',
});
// Views NODE
var NodeView = Backbone.View.extend({
el: $("#son_node_elements"),
render: function(){
var source = $("#son_node_item_templ").html();
var template = Handlebars.compile(source);
$(this.el).append(template(this.model.toJSON()));
return this;
}
});
var NodeListView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, "render");
this.collection = new Nodes();
this.collection.bind("change",this.render);
this.collection.fetch();
this.render();
},
render: function(){
_(this.collection.models).each(function(item){
var nodeView = new NodeView({model: item});
$(this.el).append(nodeView.render().el);
}, this);
}
});
Nodes = new NodeListView({el:$('#son_nodes')});
My Problem is that when this.render() is called, this.collection.fetch() is still not done and this.collection does not contain anithing to render. All works fine when I set a breakpoint at this.render() (for example using firebug), so this.render() is not called immediately. I get exactly the same result when I access a local JSON file instead of the api of my app. Any suggestions how to handle this issue?
Fetch can also be called from outside view, so let the view listen for that instead:
this.collection.bind("reset",this.render);  
Reset event will be triggered on every call to this.collection.fetch(); 
And finally, skip this.render(); Don't call this yourself, since reset event handler do this for you.
You need to call "render" inside the "success" callback for your "fetch()":
this.collection.fetch({
success: function(col) {
col.render();
}
});
That defers the rendering until the collection fetching is complete. It's all asynchronous.
Caveat: I barely know anything about Backbone in particular, but something along these lines is definitely your problem. In other words, there may be other things to worry about that I haven't mentioned (because I don't know what they are :-).

Categories