For example, something simple like the function of a login button. Would this go in the router, view, or model?
Trying to grok this! Any other explanation 开发者_C百科of what goes where would be great.
Thanks!
My general approach is to have the model's run the real logic of the application, while the views act as coordinators between the models and the HTML / interaction with the user.
In the case of a login button, you could have something simple like this:
<form>
username: <input id="username">
password: <input id="password">
<button id="login">Login</button>
</form>
with this view:
LoginView = Backbone.View.extend({
events: {
"click #login": "login"
},
login: function(e){
e.preventDefault();
model.set({
username: this.$("#username").val(),
password: this.$("#password").val()
});
model.login();
}
});
and a model that looks something like this:
User = Backbone.Model.extend({
login: function(){
var self = this;
$.post("/user/login",
this.toJSON(),
function(data){
if (data.loggedIn){
self.trigger("loggedIn", self);
}
}
});
}
});
This is a very simple example and doesn't cover many of the edge cases or what to do once you have logged in, of course. But at this point, you'll have the ability to listen to the user model's "loggedIn" event and have your application respond appropriately.
there are some edge-cases that you'll want to cover, such as not allowing someone to log in if they haven't supplied both a username and password. i've got a couple of blog posts that cover this:
http://lostechies.com/derickbailey/2011/06/15/binding-a-backbone-view-to-a-model-to-enable-and-disable-a-button/
http://lostechies.com/derickbailey/2011/08/14/enabling-and-disabling-a-button-with-backbone-modelbinding/
and you may want to employe an "event aggregator" to raise a "user:loggedIn" event instead of having the user model directly raise that event. I've covered the user of an event aggregator related to coordinating multiple views, here:
http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js/
...
of course, my style of development is only one possible style with backbone. i'd recommend searching around google and the backbone documentation to look at additional examples.
精彩评论