You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Backbone.js中实现按钮点击事件与简单函数调用?

在Backbone.js(结合Marionette)中实现按钮点击事件的正确方式

你当前维护的是采用Backbone.js+Marionette的遗留前端项目,作为新手觉得它和原生JavaScript差异明显。原生JS实现按钮点击触发函数的代码如下:

原生JavaScript实现示例

JavaScript代码

document.getElementById("myBtn").addEventListener("click", myFunction);

function myFunction(){
  alert("Hello");
}

HTML代码

<!DOCTYPE html>
<html>
<body>
    <button id="myBtn">Click me for alert</button>
</body>
</html>

你尝试用Backbone.js实现相同功能,但代码中的myFunction无法正常运行,你的尝试代码如下:

你尝试的错误实现

JavaScript代码

define(['app',
    'underscore',
    'handlebars',
    'backbone',
    'marionette',
    'i18next',
    'backbone.syphon',
    'jquery-validation'     
], function(MyApplication, _, Handlebars, Backbone, Marionette, i18n, Syphon, Validation, compiledTemplate) {

    MyApplication.module('MyModule.View', function(View, MyApplication, Backbone, Marionette, $, _) {

        View.MyView = Marionette.View.extend({
        myFunction: function(){
          alert("Hello");  // This is not working
        }
        });
    });

    return MyApplication.MyModule.View;
});

HTML代码

<!DOCTYPE html>
<html>
<body>
    <button id="myBtn" onclick="myFunction();">Click me for alert</button>
</body>
</html>

正确实现方式

Backbone(及Marionette)采用声明式事件绑定模式,不能直接在HTML中用onclick调用视图内的方法(视图方法是实例成员,并非全局函数)。以下是修正后的完整代码:

修正后的JavaScript代码

define(['app',
    'underscore',
    'handlebars',
    'backbone',
    'marionette',
    'i18next',
    'backbone.syphon',
    'jquery-validation'     
], function(MyApplication, _, Handlebars, Backbone, Marionette, i18n, Syphon, Validation, compiledTemplate) {

    MyApplication.module('MyModule.View', function(View, MyApplication, Backbone, Marionette, $, _) {

        View.MyView = Marionette.View.extend({
            // 声明事件绑定:格式为「事件类型 选择器: 视图方法名」
            events: {
                'click #myBtn': 'myFunction'
            },

            myFunction: function(){
                alert("Hello"); // 现在可正常触发
            },

            // 关联对应的HTML模板(需确保compiledTemplate指向你的模板文件)
            template: compiledTemplate
        });
    });

    return MyApplication.MyModule.View;
});

修正后的HTML模板(需移除onclick属性)

<!DOCTYPE html>
<html>
<body>
    <button id="myBtn">Click me for alert</button>
</body>
</html>

关键说明

  • 事件声明规则:在视图的events对象中配置绑定关系,Marionette会自动完成事件监听的绑定,且保证方法内的this指向视图实例。
  • 移除全局onclick:原HTML中的onclick="myFunction()"会在全局作用域查找函数,而你的myFunction是视图实例的私有方法,因此无法找到,必须移除该属性。
  • 模板关联:确保视图的template属性正确指向对应的HTML模板,这样Marionette渲染视图时才能将模板内容加载到视图DOM中,事件绑定才能生效。

如果需要手动挂载视图,需在合适的位置执行初始化和渲染操作:

// 初始化视图实例
const myView = new MyApplication.MyModule.View.MyView();
// 渲染视图
myView.render();
// 将视图DOM插入页面容器
$('#target-container').html(myView.el);

内容的提问来源于stack exchange,提问作者DNép

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 16:45:25