0

我有一个下划线 JS模板和一个jQuery 插件,它依赖于在模板可见后呈现的标记,但问题是当我准备好使用jQuery文档时,它没有得到呈现的 HTML。

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

非常感谢您的帮助!

4

1 回答 1

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。

此外,您可以使用 this.$el 代替 jQuery(this.el)。

于 2012-06-04T00:54:01.983 回答