View partials in BackboneJS
Are there any ways to use view partials in Backbone? I'm using the built in Underscore templating and there isn't much documentati开发者_开发知识库on on this.
If not, are there any standards/conventions or suggested ways of doing this?
Yes, I have tried this recently. Make sure to read on the Backbone documentation, particularly the View section.
For example, you have a _new.jst.haml:
%form#story_form.new_story{method: "post"}
Then, you can have a _form.jst.haml that contains the form elements. In your Backbone.View, you can first append the new template in your el, followed by using the view-scoped selectors of Backbone (this is in their official documentation, under "$(jQuery or Zepto)" section):
$(this.el).html(window.JST['stories/_new'](attrs));
...
this.$('#story_form').html(window.JST['stories/_form'](attrs));
I was using Rails and so I initially read up on using Backbone.js with Rails from this article. There's a link to a part 2 at the end of that article. I suggest you skip the part in the first article where he uses string concatenation for updating the views. Also, my approach now is quite different from how he did it, but I think it's a pretty good starting point, and I don't have my own article to show for anyway.
My code examples are somewhat short, but I guess I don't want to write an entire tutorial here. Just let me know what doesn't work, and what step you think is missing and I'll update the answer.
Yes, you can use partials in your templates and you don't have to set them up in your View class, you can do it right from your templates. Here's a simple example:
users.jst:
<ul>
<% _.each(users, function(user){ %>
<li>
<%= JST['user']({user: user}) %>
</li>
<% }); %>
</ul>
user.jst:
<%= user.get('name') %>
There are many "vanilla" Backbone ways to do this, but I'd highly recommend looking into MarionetteJS, Backbone.CollectionView or Backbone.LayoutManager. There's alot to keep track of when rendering collections for example (unbinding events on child removal, selector scope, keeping sort order), and there's no need to reinvent the wheel.
- MarionetteJS
- LayoutManager
- CollectionView
- Backbone.Babysitter
精彩评论