【问题标题】:Using inline jQuery with Handlebars.js templates?将内联 jQuery 与 Handlebars.js 模板一起使用?
【发布时间】:2012-07-29 15:55:02
【问题描述】:

我使用 Sammy.js 处理路由/应用程序逻辑,使用 Handlebars.js 进行模板化。我想设置一些简单的 jQuery 事件来使 UI 动态化(切换元素等)。例如:

$("#availability").click( function(e) {
    console.log("hi2");
    e.preventDefault();
});

目前,我可以通过将 jQuery 事件放在 Sammy.js 应用程序中来做到这一点,但这感觉非常混乱:

this.get('#q=:query', function(context) {
    var query = context.params.query,
    loadOptions =   {
                      type: 'get', 
                      dataType: 'json',
                      data: {query: query},
                      cache: CACHE_ENABLED
                    };

    context.load("search.php", loadOptions)
            .then(function(products) {
                 context.query = query;
                 context.products = products.hits.hits;                         
                 return context;
            })
            .partial('/js/templates/search.hb')
            .replace('body')
            .then( function () {
                $("#availability").click( function(e) {
                    console.log("hi2");
                    e.preventDefault();
                });
            });
});

有没有办法在 Handlebars 模板本身或使用 Helper 初始化这些类型的 jQuery 事件?我尝试注册一些自定义助手,但这些事件从未被触发。

我希望将“UI Logic”与主应用程序逻辑分开,因为它会使我的主 Sammy.js 代码变得混乱,并且难以阅读。

【问题讨论】:

    标签: jquery handlebars.js sammy.js


    【解决方案1】:

    仍然没有找到在 Handlebars 模板中包含内联 jQuery 的方法,但我找到了将其包含在 Sammy 应用程序中的更好方法。我已将代码删除到 Sammy Helper 并调用它,这有助于整理应用程序的主要部分。

    var app = Sammy("body", function() {
    
        this.use('Handlebars', 'hb');
    
        this.helpers({
             jq_clickEvents: function() {
                 $("#availability").click( function(e) {
                        console.log("hi2");
                        e.preventDefault();
                  });
    
             }
        });
    
        this.get('#q=:query', function(context) {
            var query = context.params.query,
            loadOptions =   {
                      type: 'get', 
                      dataType: 'json',
                      data: {query: query},
                      cache: CACHE_ENABLED
                    };
    
             context.load("search.php", loadOptions)
                    .then(function(products) {
                        context.query = query;
                        context.products = products.hits.hits;                         
                        return context;
                     })
                    .partial('/js/templates/search.hb')
                    .replace('body')
                    .then('jq_clickEvents');
         });
    });
    

    【讨论】:

      猜你喜欢
      • 2012-01-29
      • 2013-03-31
      • 1970-01-01
      • 2011-06-03
      • 2017-09-02
      • 2023-03-06
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多