Reputation: 2970
I have an underscore JS template and a jQuery plug-in that depends on the markup that gets rendered after the template is visible, but the problem is when I use jQuery document ready, it doesn't get the HTML that is rendered.
I used domReady
but still ain't working, how can I accomplish this probably? This is what I got so far:
main.js
requirejs.config({
baseUrl: 'js/modules',
shim: {
// 'jquery.colorize': ['jquery'],
// 'jquery.scroll': {
// deps: ['jquery'],
// exports: 'jQuery.fn.colorize'
// },
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'underscore': {
deps: ['jquery'],
exports: '_'
}
},
paths: {
'jquery': '../libs/jquery',
'underscore': '../libs/underscore',
'backbone': '../libs/backbone',
'text': '../libs/text',
'views': '../views',
'templates': '../../templates',
'domReady': '../libs/domReady',
'ui': '../ui'
}
});
requirejs(['homeView', 'ui/placeholder'], function(Main){
Main.initialize();
});
homeView.js
define(['jquery', 'underscore', 'backbone', 'text!templates/home.html'], function($, _, Backbone, homeTemplate){
var HomeView = Backbone.View.extend({
el: $("#application"),
events: function(){
// Empty.
},
initialize: function(){
// Empty.
},
render: function(){
$('body').addClass('pt-dark');
$(this.el).html(_.template(homeTemplate, {}));
}
});
return new HomeView;
});
ui/placeholder.js
requirejs(['domReady', 'jquery'], function(doc, $){
doc(function(){
// Empty should contain the template html at this point.
console.log($('body').html());
});
});
Thanks a lot for help!
Upvotes: 0
Views: 677
Reputation: 1758
Try this:
define(['jquery', 'underscore', 'backbone', 'text!templates/home.html'], function($, _, Backbone, homeTemplate){
var HomeView = Backbone.View.extend({
el: $("#application"),
template: _.template(homeTemplate),
events: function(){
// Empty.
},
initialize: function(){
// Empty.
},
render: function(){
$('body').addClass('pt-dark');
this.$el.html(this.template({})));
jQuery('#the_thing_you_need', this.$el).theFunctionYouNeed();
}
});
return new HomeView;
});
Note that you should define a local attribute to the view called 'template' or something of that sort to store your template in and not re-call _.template every time that you need it.
Also, instead of jQuery(this.el) you can use this.$el.
Upvotes: 1