Normally when I use jquery to build a simple app to show data, I would simply change some global variables depending on certain actions and then when I was ready to retrieve data from the server, I'd pass those vars along to the server.
What is a good way to do this in开发者_Go百科 backbone.js? Does my view handle that? I have this view so far:
var ListView = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
template = _.template("\
<table>\
<% _(collection).each(function(model){%>\
<tr><td><%=model.name%></td><td><%=model.email%></td></tr>\
<%}); %>\
</table>\
");
var context = {collection: this.collection.toJSON()};
$(this.el).html(template(context));
$('#app').html(this.el);
}
});
Basically in my controller I create a users
collection and then I use users.fetch()
and then pass the users
collection to a new ListView
object. The initialize function automatically renders (is this bad practice?) I know there's events in backbone.js, and I'm guessing that's where this needs to end up. How do I handle sorting by certain fields or searching for certain text in certain fields or choosing how many results come back (i.e. 10 per page), etc.?
Since backbone.js uses a RESTfull Api it's not so easy. You would have to override the Backbone.sync READ method to construct your own URL call: How to override Backbone.sync?
This might help you as well: REST API Best practices: Where to put parameters?
I would render then, when you have gotten back the data you need. Initialize will be called on var listview = new ListView(), and if you don't have the data bootstrapped - probably nothing will happen.
You can use set the comparator like this:
http://documentcloud.github.com/backbone/#Collection-comparator
var Chapter = Backbone.Model;
var chapters = new Backbone.Collection;
chapters.comparator = function(chapter) {
return chapter.get("page");
};
chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));
alert(chapters.pluck('title'));
you can use Collection.sort()
http://documentcloud.github.com/backbone/#Collection-sort
or you can use Underscore methods and manually reset the collection http://documentcloud.github.com/backbone/#Collection-Underscore-Methods
http://documentcloud.github.com/backbone/#Collection-reset
精彩评论