0

我正在评估将一些 jQuery 代码移动到 Backbone 并且有一个完全的菜鸟问题。我有大量仅存在于标准 html 上的 jQuery 事件(与主干视图无关)。处理这些的合适的地方是什么。jQuery中的一些简单的东西:

<div class='my-thing'>click me</div>
<script>
  $(document).ready(function(){
     $('.my-thing').on('click',function(){
       alert('say hello');
     });
  });
</script>

在 Backbone 中,它似乎是这样的:

events: {
     "mouseenter .my-thing":"say_again"
 },
 say_again: function(){
   alert('i want to say something');
 },

但我会把这个放在哪里?或者构造这个?

提前谢谢

4

1 回答 1

2

通常你会按视图组织它们——这就是你声明事件的地方。这需要模块化 UI 的布局,以便将每个事件限制在视图范围内。

模板

<script type='text/template' id='say-template'>
    <div class='say-container'>
        <div class='my-thing'>click me</div>
    </div>
</script>

看法

var SayView = Backbone.View.extend({
    initialize: function() {
        _.bindAll(this, "render");
        this.render();
    },

    el: "#container",

    template: _.template($("#say-template").html()),

    events: {
        "mouseenter .my-thing": "say_again"
    },

    say_again: function() {
        alert('i want to say...');
    },

    render: function() {
        this.$el.html(this.template());
    }
});

var sayView = new SayView();

HTML

<div id="container"></div>

这是一个工作演示。


Of course, nothing is stopping you from wiring up events in the normal way in the global scope of the application, if you need to. It's just best to avoid as doing that tends to break the MVC pattern.

于 2012-11-21T03:49:45.373 回答