Reputation: 19929
Just starting to use backbone and have a quick question and thought I'd write a simple message board. I want to have something that responds to the hash change detail/:id and have added this to the router like this. This seems to work but I don't think this is the proper way of doing this. Is this, in general, how a http call get an object would take place (specifically the success callback)?
var MessageBoardRouter = Backbone.Router.extend({
routes: {
"detail/:id" : "showDetail"//,
},
showDetail: function(id){
console.log('within showDetail with ' + id);
//var p1=new Post({header:'my original header'});
var p2=new Post({id:id});
p2.fetch({
success: function(){ // <- should I be doing this or different way or is who strategy off???
console.log(p2.attributes);
var view= new MbDetail();
view.render(p2);
}
});
},
thx in advance
Upvotes: 0
Views: 65
Reputation: 1294
The approach of binding to a change
event can work well generally if you want a consistant reaction to every event.
Backbone fetch returns a jqXHR object which can be used with Deferred objects. I find that this approach generally looks better.
This is how it would look:
var MessageBoardRouter = Backbone.Router.extend({
routes: {
"detail/:id" : "showDetail"//,
},
showDetail: function(id){
console.log('within showDetail with ' + id);
//var p1=new Post({header:'my original header'});
var p2=new Post({id:id});
var view= new MbDetail();
p2.fetch().done(function() {
view.render(p2);
console.log(p2.attributes);
});
},
Upvotes: 0
Reputation: 146004
There are 2 ways to respond to backbone events: with a callback (like you have above) or with event bindings. I believe event bindings to be the more idiomatic and "backboney" approach for the general case for the following reasons:
However, with that in mind, both styles will work just fine. In your specific example, you might want to code it like this:
var p2=new Post({id:id});
p2.on('change', function(post){
console.log(post.attributes);
var view= new MbDetail();
view.render(p2);
}
p2.fetch();
Some other ancillary points:
render()
. It's not designed to expect them. Pass the model to the view via the options.model
constructor argument, then reference the model from within render
as needed.Upvotes: 1