2012-06-02 29 views
0

我有一个强调JS模板和jQuery插件取决于之后的模板是可见的是被渲染的标记,但问题是,当我使用jQuery文档已准备好,它不会获取呈现的HTML。要求JS骨干JS jQuery的模板标记依靠

我用domReady但还是不行,我该怎么做到这一点呢?这是我走到这一步:

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()); 
    }); 
}); 

非常感谢您的帮助!

+1

您在homeView.render()中无法做到这一点的任何特定原因,或者让这个其他插件触发了一个调用?它不工作,因为你在domReady和homeView.render()实际插入你的html之间进行竞赛。 – radicand

+0

@radicand我使用data-api元素,所以jQuery插件需要模板内容,这可能是正确的吗? – onlineracoon

回答

1

试试这个:每次

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; 
}); 

请注意,您应该定义一个本地属性,称为“模板”或诸如此类的东西视图模板存储,而不是重新调用_.template那你需要它。

此外,而不是jQuery(this.el),您可以使用此。$ el。