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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With