JavaScript 返回不同的值

标签 javascript jquery backbone.js

我正在创建一个简单的 Backbone.js 待办事项列表。

在我的 View 初始化中,我有:

    var TodoView = Backbone.View.extend({
        render: function() {
            var html = '<input type="text" value="' + this.model.get('title') + '">';
            $(this.el).html(html);
        },
       initialize: function () {
            var thisView = this;
            console.log(thisView.model.toJSON()); // <- this works
            $(this.el).change(function (thisView) {
                console.log(thisView.model.toJSON()); // <- thisView is not View here
                thisView.model.set('title', $(this).val());
            });
       }
    });

我也尝试过这个:

       setTitle: function () {
           console.log(this); // <- this doesn't return View
       },

       initialize: function () {
           $(this.el).change(this.setTitle)
       }

最佳答案

Javascript 中的 changeclick 和其他 jQuery“事件”方法的回调仅采用一个参数:触发的事件。

var TodoView = Backbone.View.extend({
    render: function() {
        var html = '<input type="text" value="' + this.model.get('title') + '">';
        $(this.el).html(html);
    },
   initialize: function () {
        var thisView = this;
        console.log(thisView.model.toJSON()); // <- this works
        $(this.el).change(function (event) {
            console.log(thisView.model.toJSON()); // <- this works also
            thisView.model.set('title', $(this).val());
        });
   }
});

但是你不应该这样做。您几乎不应该直接调用 jQuery $。您应该使用 View 的事件属性。

对于第二部分,您可以执行以下操作:

initialize: function () {
    var view = this;
    $(this.el).change(function () {
        view.setTitle();
    });
}

或者这个:

initialize: function () {
    var view = this;
    // Beware: the first and only argument that setTitle() will receive is the event
    $(this.el).change(this.setTitle.bind(this));
}

关于JavaScript 返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32762351/

相关文章:

javascript - 在 Recaptcha.reload() 完成后执行代码

javascript - p5 : resize canvas, 具有固定的起始宽度/高度?

javascript - 在 JavaScript 中显示文本文件

javascript - JS表格按复选框排序

backbone.js - Backbone : restore model's attributes value after a failed save with patch:true

javascript - 点击时不加载 JQuery 切换功能,仅在第 3 次点击时加载

jquery - 使用 bootbox.confirm() 确认表单提交

javascript - 访问存储在对象中的数据

javascript - 绑定(bind)到表单时的主干模型状态

backbone.js - 主干中的选项卡