Javascript Backbone 0.9.9:listenTo 和 on 之间的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14041042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:31:45  来源:igfitidea点击:

Backbone 0.9.9: Difference between listenTo and on

javascripteventsbackbone.jsbackbone-events

提问by bodokaiser

I am trying to learn the new changes they did in Backbone 0.9.9.

我正在尝试学习他们在 Backbone 0.9.9 中所做的新更改。

Currently I got problems to understand the difference between listenToand on:

目前,我有问题理解之间的区别listenToon

listenTo

var View = Backbone.View.extend({

    tagName: "div",

    intialize: function() {
        this.listenTo(this.model, 'change', this.render);
    },

    render: function() {
        this.$el.empty();
        this.$el.append('<p>hello world</p>');
    }

});

on

var View = Backbone.View.extend({

    tagName: "div",

    intialize: function() {
        this.model.on('change', this.render, this);
    },

    render: function() {
        this.$el.empty();
        this.$el.append('<p>hello world</p>');
    }

});

I have heard that listenToallows with stopListeningto unsubscribe from all events when for example the view gets removed to avoid memory leaks.

我听说当例如视图被删除以避免内存泄漏时,listenTo允许stopListening取消订阅所有事件。

Is this the only reason?

这是唯一的原因吗?

采纳答案by Derick Bailey

listenToand stopListeningcame from the community, basically. They help to make it easier to bind and unbind events.

listenTostopListening来自社会,基本上是这样。它们有助于更轻松地绑定和解除绑定事件。

There's a lot of existing documentation and blog posts surrounding the idea, including stuff that I've written on the subject.

有很多现有的文档和博客文章围绕着这个想法,包括我写的关于这个主题的东西。

Johnny Oshika is the first person that I saw using this technique. It was originally posted as an answer to a StackOverflow question here: Backbone.js : repopulate or recreate the view?

Johnny Oshika 是我看到的第一个使用这种技术的人。它最初是作为对 StackOverflow 问题的回答发布的:Backbone.js : repopulate or recreate the view?

You can read what I've written about this, here:

你可以在这里阅读我写的关于这个的内容:

回答by Richard

When you create a view, both listenToand onadd event handling. However, when the view is destroyed, the listenTocall will automatically remove the event handler. This prevents memory leaksand zombie event listeners.

当你创建一个视图,都listenToon添加事件处理。但是,当视图被销毁时,listenTo调用将自动删除事件处理程序。这可以防止内存泄漏和僵尸事件侦听器。

So, use onif you want to manage the handler yourself. Just make sure to call off. Otherwise, call listenTo.

因此,on如果您想自己管理处理程序,请使用。只要确保调用off. 否则,调用listenTo