0

我在 stackoverflow 上的第一篇文章。(而且英语不是我的母语)。

我正在尝试学习如何使用 emberjs。由于缺乏好的教程,这并不容易。

所以我决定编写一个聊天代码,我使用 nodejs 和 socket.io 服务器端。

html

<script type="text/x-handlebars">
<div class="page">

    <div class="users">
    </div>

    <div class="messagebox">
        {{#view App.TextField valueBinding="currentMsg" placeholder="your message"}}{{/view}}

        <button {{action "sendMsg"}}>Send</button>
    </div>

    <div id="chatbox">
    {{#collection contentBinding="App.MsgsController" tagName="ul"}}
        <b>{{value}}</b>
    {{/collection}}
    </div>
</div>
</script>

Javascript

var id;

var socketio = io.connect("127.0.0.1:8888");
socketio.on('id', function (data) {
    id = data;
});
socketio.on("broadcast", function (data) {
    if (id == data.id) {
        return
    }
    App.MsgsController.addMsg(data.message);

});
socketio.on("own", function (data) {
    App.MsgsController.addMsg(data.message);
});



App = Ember.Application.create();

App.Msg = Ember.Object.extend({
    value: null
});

App.MsgsController = Ember.ArrayController.create({
    content: [],
    addMsg: function (value) {
        var msg = App.Msg.create({
            value: value
        });
        this.pushObject(msg);
    }
});

App.TextField = Ember.TextField.extend({
    insertNewline: function() {
        this.get("controller").send("sendMsg");
    }
});

App.ApplicationController = Ember.Controller.extend({
    currentMsg: 't',
    sendMsg: function () {
        var currentMsg = this.get('currentMsg');
        if(currentMsg) {
            socketio.emit("message", { message: currentMsg, id: id});
            this.set('currentMsg', '');
        }
    }
});

我想在 App.ApplicationController.sendMsg 调用之后关注 App.TextField。

我试过了

App.TextField.$().focus()

但似乎我只能在其方法中使用 $() 。

有人可以帮助我吗?

编辑:好的,我找到了答案。

App.TextField 就像“类”,视图上的就是一个实例。

我必须在我的视图中添加一个 id

{{#view App.TextField valueBinding="currentMsg" placeholder="your message" id="mytextfield"}}{{/view}}

并使用 jquery 选择器访问实例

$('#mytextfield').focus();
4

1 回答 1

0

使用 didInsertElement 钩子让视图处理 jquery 方法。

http://emberjs.com/api/classes/Ember.View.html#event_didInsertElement

于 2013-08-07T15:34:45.293 回答