Reputation: 1250
Is there a fancy way of binding a view to html already renderer in the page?
Example your server load all your page html, then you load views on top of that html without using the render method the first time you load the page.
Upvotes: 5
Views: 3191
Reputation: 10993
I'm not sure what you mean by a fancy method, but your views don't need to render the html
for their el
themselves. You can easily attach a view to an existing element on the page just by assigning it to it's el. If you want to assign your view's el at a later point (say you want to "switch" its el
) then you can use the setElement method to do so. Using the setElement
will also create the cached $el
and move over any bound events.
Upvotes: 1
Reputation: 370
I've done something similar to what I think you're trying to do. In my case, I added Backbone functionality on top of existing forms. Here's a stripped down example:
Existing HTML:
<div id="my-app">
<form name="input" action="html_form_action.asp" method="get">
Username: <input type="text" name="user" id="username" />
<input type="submit" value="Submit" />
</form>
</div>
Backbone:
var MyFormView = Backbone.View.extend({
events: {
"submit form": "formHandler"
},
formHandler: function(evt) {
evt.preventDefault();
var nameVal = $('#username').val();
this.$el.append('<p>hello: ' + nameVal + '</p>');
}
});
$().ready(function(){
var myForm = new MyFormView({el: "#my-app"});
});
The key is passing your existing html as the "el" property when you create your view.
Upvotes: 10
Reputation: 9358
I'm not exactly sure what you are currently working on, but I made a JSFiddle that utilizes only Backbone Views - no Models or Collections or Routers to worry about.
You can play around with this and see how the main page view is being loaded into its container.
Here is the Fiddle: http://jsfiddle.net/phillipkregg/tVmTM/71/
Upvotes: 0