backbone.js 中的绑定和 _.bindAll

2024-03-17

我对绑定及其目的感到困惑_bind.All在backbone.js中。下面是创建模态视图的工作代码#modal并渲染从后端获取的评论。

首先,在下面的代码中,我在initialize功能_.bindAll(this, 'render', 'renderComments');。不管我做与不做_.bindAll(), 我打电话没有问题this.render() and this.renderComments() inside initialize()。有没有什么时候的例子_.bindAll()会帮助我们,什么时候不会?

ModalView = Backbone.View.extend({
    el: $('#modal'),

    template: _.template( $('#tpl_modal').html() ),

    initialize: function() {
        _.bindAll(this, 'render', 'renderComments');
        this.render();
        this.renderComments();
    },

    render: function() {
        $(this.el).fadeIn('fast').append( this.template( this.model.toJSON( this.model ) ) );
    },

    renderComments: function() {
        this.commentList = new CommentCollection();
        var self = this;
        this.commentList.fetch({
            data: { post_id: this.model.id},
            processData: true,
            success: function() {
                self.commentListView = new CommentListView({ collection: self.commentList });
            }
        });
    }
});

And

CommentListView = Backbone.View.extend({
    el: '.modal_comments',

    initialize: function() {
        this.render();
    },

    render: function() {
        var self = this;
        this.collection.each( function(comment, index) {
            $(self.el).append( new CommentListItemView({ model: comment }).render().el );
        });
        return this;
    }
});

其次,我对前置感到困惑this.对某事。例如在renderComments,为什么我不能使用:

var commentList = new CommentCollection();
var self = this;
commentList.fetch({.... });

对于线路this.commentList = new CommentCollection();,除了实例化类之外CommentCollection(),它是否使commentList的孩子ModalView?

另外,是否需要有var self = this;并使用self.commentListView稍后在回调函数中?可以使用绑定以便我可以访问吗this.commentListView,或者正在使用var self = this传统的做事方式?

最后,应该self.commentListView = new CommentListView({ collection: self.commentList });在成功函数中renderComments被移至CommentListView的初始化方法代替并绑定到this.collection.on('reset');防止嵌套太多函数?这将导致:

ModalView = Backbone.View.extend({
    el: $('#modal'),

    template: _.template( $('#tpl_modal').html() ),

    initialize: function() {
        _.bindAll(this, 'render', 'renderComments');
        this.render();
        this.renderComments();
    },

    render: function() {
        $(this.el).fadeIn('fast').append( this.template( this.model.toJSON( this.model ) ) );
    },

    renderComments: function() {
        this.commentList = new CommentCollection();
        this.commentListView = new CommentListView({ collection: this.commentList });
        this.commentList.fetch({
            data: { post_id: this.model.id},
            processData: true
        });
    }
});

CommentListView = Backbone.View.extend({
    el: '.modal_comments',

    initialize: function() {
        this.collection.on('reset', this.render, this);
    },

    render: function() {
        var self = this;
        this.collection.each( function(comment, index) {
            $(self.el).append( new CommentListItemView({ model: comment }).render().el );
        });
        return this;
    }
});

唷——长问题;)

1)我曾经做过_.bindAll当我第一次使用骨干网时,在我的初始化方法中,但后来我停止了。通常不需要它,除非您绑定到事件,然后它确实很有帮助。例如,如果您有:

events:
{
    'click': clickHandler
},
clickHandler: function(){
    //do cool stuff
}

那么这样做会很有帮助_.bindAll(this, 'clickHandler')否则你的this指针不会是视图

2)如果我理解你的问题:commentList成为您的实例的属性ModalView.

3)使用var self = this;相对常见,但在许多情况下可以避免,因为 Underscore.js 中的重载(这是backbone.js 的依赖项)。例如,大多数集合函数(map, each等)将上下文作为最后一个参数。所以而不是

var self = this;
_.map([1,2], function(item){
    self.sum = self.sum + item; 
});

你可以做:

_.map([1,2], function(item){
    this.sum = this.sum + item; 
}, this);

如果你的情况你可以更换你的success方法与

success: _.bind(function() {
             this.commentListView = new CommentListView({ collection: this.commentList });
         }, this);

如果您想了解有关本指南中有些令人困惑的主题的更多信息,建议您阅读以下优秀教程:http://bonsaiden.github.com/JavaScript-Garden/#function.this http://bonsaiden.github.com/JavaScript-Garden/#function.this

4)是的——我会将渲染移至reset。这样,如果其他原因导致集合重置,视图将拾取它。

希望我回答了你所有的问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

backbone.js 中的绑定和 _.bindAll 的相关文章

  • 可以在 d3.js 中使用具有固定圆圈大小的圆圈包布局吗?

    此圆形包布局示例 http bl ocks org 4063269 http bl ocks org 4063269 非常适合我正在从事的项目 但是它会调整所有圆圈相对于彼此的大小 有没有一种简单的方法来指定每个圆的固定半径 我已经搜索了源
  • Backbone:仅当事件侦听器尚不存在时才添加

    换句话说 如何找到已收听的事件列表 我正在使用 Backbone on 和 Backbone trigger 在两个彼此不了解的视图之间进行通信 但是 添加侦听器的视图实际上是一个 项目视图 一个集合 所以我添加了许多侦听器 因此我想首先检
  • 如何禁用 Firebase 电话身份验证 reCAPTCHA? (网络/反应)

    我正在构建一个 React Firebase 应用程序并使用 Firebase 的 PhoneAuthProvider 进行身份验证 在开发过程中 需要进行大量的登录和注销来测试身份验证流程 私有路由 登录重定向等 每次我需要登录时 都会向
  • React 和 ES6 继承

    Note 这篇文章是在 React 不支持 ES6 v12 时发布的 我有一个 ES6 课程 class BaseClass getInitialState return message Hello render return div di
  • 如何从 JQuery - IonRangeSlider 获取值?

    我怎样才能得到低值和高值ion rangeSlider http ionden com a plugins ion rangeSlider en html通过单击按钮来组件 这是我的 jQuery 代码
  • 在 Woocommerce 结帐中启用特定状态的交货时间选项

    基于 在 WooCommerce 结帐中添加自定义复选框 其值显示在管理员编辑订单中 https stackoverflow com questions 45905237 add a custom checkbox in woocommer
  • 是否可以使用 JavaScript 导入 HTML?

    我有一些具有相同页脚的 html 页面 使用 JavaScript 并且仅使用 JavaScript 我可以在其中导入另一个 html 页面吗 下面介绍了如何仅使用 JavaScript 向页面添加页脚 2022 代码 使用fetch ht
  • fs.statSync 与缓冲区“错误:路径必须是没有空字节的字符串”

    我已经读入这样的文件缓冲区 let imageBuffer try imageBuffer fs readFileSync some path to image jpg catch e console log error reading i
  • 保持 WebSocket 连接处于活动状态

    我正在研究 WebSocket 协议 并尝试在后端使用 Python 实现一个简单的 ECHO 服务 它似乎工作正常 但连接建立后立即断开 这是我的客户
  • 为什么闭包编译器不缩短这个?

    我不确定这只是一个错误还是一个预期的功能 基本上 我有这个微小的功能 我现在看到end这里是蓝色的 但这工作得很好 如果我将其重命名为其他名称 我仍然遇到问题 function f a b var start Math min a b va
  • jQuery 在页面上查找电话号码并包含在 链接中

    这是一个与这个从未得到解答的老问题类似的问题 使用 jquery 将 https stackoverflow com questions 4607753 wrap a tag around phone number using jquery
  • TinyMCE没有定义Jquery

    已经解决这个错误 2 天了 但无法让 TinyMCE 工作 我正在使用 TinyMCE 的 jquery 版本 下面是我的 HTML 代码 其中包含一个包含文本区域的表单 我使用 Google Inspect Element 在控制台选项卡
  • 使用 JS 从列表中删除最近的 元素的 URL

    所以我有一个网址列表 并且有删除按钮 图像按钮 当点击删除按钮时 按钮旁边的 url 必须从列表中删除 let list const remove document getElementById remove const view docu
  • Highcharts 异步服务器加载多个系列

    我正在尝试按照其示例使用 Highcharts 的延迟加载 http www highcharts com stock demo lazy loading http www highcharts com stock demo lazy lo
  • 根据传单中的属性更改标记颜色

    我的目标是让我的标记根据它们的不同而采用三种不同的颜色rating财产 我看过类似的帖子 其中使用对象来定义颜色 每个标记都有一个rating属性在 1 到 5 之间 我正在考虑使用 else if 语句 例如 if rating lt 3
  • 利用源映射的堆栈跟踪

    概述 浏览器控制台中的堆栈跟踪输出与调用 Error stack 时返回的跟踪不同 控制台堆栈跟踪似乎考虑了源映射 而 Error stack 堆栈跟踪则没有 控制台输出这是输出到控制台的默认堆栈跟踪 Uncaught TypeError
  • 如何使用 javascript 获取 html5 视频的缩略图?

    我找到了根据 URL 获取视频缩略图的 JavaScript 代码 不过 我只在 YouTube 和 Vimeo 上找到了这个 似乎没有人列出如何处理旨在嵌入 html5 视频标签的视频的示例 能做到吗 谢谢 是的 您可以使用视频作为画布的
  • React.js 的状态基于其他状态

    我遇到了 React js 的一些问题 并且在调用 setState 时状态没有立即设置 我不确定是否有更好的方法来解决这个问题 或者这是否真的只是 React 的一个缺点 我有两个状态变量 其中一个基于另一个 原始问题的小提琴 http
  • 如何将react-native与php一起使用并获取返回数据始终为空

    我的回报始终为空 我似乎无法让它发挥作用 我如何将react native与php一起使用并获取json 任何人都可以帮忙吗 PHP myArray array myArray lat POST lat myArray lng POST l
  • 如何在javascript中访问请求查询字符串参数?

    我见过许多利用 RegEx 的解决方案 坦率地说 这似乎有些可笑 因为 javascript 是如此通用 必须有一种更简单的方法来访问请求参数 有人可以给我演示一下吗 我发现了一个有用的方法网的深度 http www dotnetbull

随机推荐