I have a simple form as a template and an initialize method to change the textarea as required. The problem is that I want to target the textarea in order to use Jquery on it but Backbone won’t let me. For example, if I want to do this.$('textarea').css('height', '1em'); instead returns the following in the console:
[prevObject: jQuery.fn.jQuery.init[1], context: <form>, selector: "textarea"]
context: <form>
length: 0
prevObject: jQuery.fn.jQuery.init[1]
selector: "textarea"
__proto__: Object[0]
I get a similar result if I try this.$el.find('textarea').css('height', '1em').
This is my code:
template
<script id="reply-form" type="text/template">
<fieldset>
<textarea rows="3"></textarea>
<input type="button" class="cancel btn btn-small" value="Cancel">
<input type="button" class="send btn btn-success btn-small" value="Send">
</fieldset>
</script>
views.js
App.Views.Form = Backbone.View.extend({
tagName: 'form',
initialize: function() {
this.startTextarea();
},
startTextarea: function(){
console.log(this.$('textarea').css('height', '1em'));
},
template: _.template( $('#reply-form').html() ),
render: function() {
this.$el.html( this.template() );
return this;
}
What can be happening?
You can’t really modify the HTML in this way in the
initializefunction, since the template hasn’t been rendered yet — it’s not going to find anything.I think the way to do this is to place the style stuff in the template, or in a CSS file — that’s really where it belongs. But if you need to modify the template dynamically when you load the view, you’d have to do it before compiling the template. See here for an example.