当打开时,由jquery触发按键,我的模型未定义

时间:2013-12-11 00:27:16

标签: javascript backbone.js requirejs

我正在使用require.js和backbone.js构建我的应用程序。在我的一个观点中:

    define(['backbone', 'models/message', 'text!templates/message-send.html'], function (Backbone, Message, messageSendTemplate) {
    var MessageSendView = Backbone.View.extend({
        el: $('#send-message'),
        template: _.template(messageSendTemplate),
        events: {
            "click #send": "sendMessage",
            "keypress #field": "sendMessageOnEnter",
        },
        initialize: function () {
            _.bindAll(this,'render', 'sendMessage', 'sendMessageOnEnter');
            this.render();
        },
        render: function () {
            this.$el.html(this.template);
            this.delegateEvents();
            return this;
        },
        sendMessage: function () {
            var Message = Message.extend({
                noIoBind: true
            });
            var attrs = {
                message: this.$('#field').val(),
                username: this.$('#username').text()
            };

            var message = new Message(attrs);
            message.save();

            /*
        socket.emit('message:create', {
            message: this.$('#field').val(),
            username: this.$('#username').text()
        });
        */

            this.$('#field').val("");
        },
        sendMessageOnEnter: function (e) {
            if (e.keyCode == 13) {
                this.sendMessage();
            }
        }
    });
    return MessageSendView;
});

当jquery触发keypress事件并调用 sendMessage 函数时 - 由于某种原因,消息模型未定义,但是当这个视图首次由require.js加载时,它是可用的。任何提示? 感谢

2 个答案:

答案 0 :(得分:1)

请参阅我的内联评论:

sendMessage: function () {
        // first you declare a Message object, default to undefined
        // then you refrence to a Message variable from the function scope, which will in turn reference to your Message variable defined in step 1 
        // then you call extend method of this referenced Message variable which is currently undefined, so you see the point
        var Message = Message.extend({
            noIoBind: true
        });
        // to correct, you can rename Message to other name, e.g.
        var MessageNoIOBind = Message.extend ... 
        ... 
    },

答案 1 :(得分:0)

我的猜测是,您已将sendMessageOnEnter绑定为代码中其他位置的keypress事件处理程序。通过这样做,您将在调用绑定事件处理程序的函数时更改this的上下文。基本上,当你调用this.sendMessage()时,this不再是你的MessageSendView对象,它很可能是你绑定keypress事件的jQuery元素。由于您正在使用jQuery,因此您可以通过使用$ .proxy将sendMessageOnEnter函数绑定到正确的上下文来解决此问题。类似的东西:(注意 - 这根本没有测试过)

var view = new MessageSendView();

$('input').keypress(function() {
  $.proxy(view.sendMessageOnEnter, view);
});

我希望这会有所帮助,这里有一些更适合你的阅读。快乐的编码!

Binding Scopes in JavaScript

$.proxy