Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a backbone view to html already renderer

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.

like image 877
The Orca Avatar asked Sep 19 '12 16:09

The Orca


2 Answers

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.

like image 169
squaretone Avatar answered Oct 27 '22 03:10

squaretone


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.

like image 40
Jack Avatar answered Oct 27 '22 03:10

Jack