简体   繁体   English

在jQuery事件处理程序闭包中使用Ember.js模型

[英]Use an Ember.js model in a jQuery event handler closure

I'm trying to create a sortable list of items. 我正在尝试创建可排序的项目列表。 At this moment I'm using jQuery sortable for this. 目前,我正在为此使用jQuery sortable。 The list is created using an Ember view. 该列表是使用Ember视图创建的。 When an item is dropped I would like the Ember model to be updated with the new order. 放下物品时,我希望用新订单更新Ember模型。 At a later stage I would like to save this back to the server. 在稍后的阶段,我想将其保存回服务器。

In the code below you can see how I've attached the jQuery code to the view elements. 在下面的代码中,您可以看到我如何将jQuery代码附加到view元素。 Dragging itself works perfectly and the stop function is also called. 拖动本身可以完美工作,并且还调用了stop函数。

Scrum.Sortable  = Ember.View.extend({
tagName :   'div',
didInsertElement:   function(){
    this.$().sortable({
        placeholder: "ui-state-highlight",
        stop:function(){
            var order   = 1;
            $('div.pb-item').children().each(function(index){
                $(this).find('.order').each(function(){
                    //
                    // Access and save the model here
                    //
                    $(this).html(order++);
                });
            });
        }
    });

}
});

You can also see I manually update the view html. 您还可以看到我手动更新了HTML视图。 This is what I would like to store in the model. 这就是我要存储在模型中的内容。 Unfortunatly I can't seem to access the model. 不幸的是,我似乎无法访问该模型。

Any ideas on how to do this are greatly appreciated. 任何有关如何执行此操作的想法将不胜感激。

Thanks. 谢谢。

Just save a reference to your controller outside the function so that the variable is visible in the closure. 只需在函数外保存对控制器的引用,以使变量在闭包中可见。 Then you'll have access to the controller and hence your model, etc. 然后,您将可以访问控制器,从而可以访问模型等。

didInsertElement: function() {
  controller = this.get('controller')
  ...
    $(this).find('.order').each(function(){
      // Here you have access to the controller variable.
    });
  ...
}

Since the controller generally stays the same throughout the whole life of the view, this is safe, and is better than saving a reference to your model itself, because your model may change. 由于控制器通常在视图的整个生命周期中保持不变,因此这是安全的,并且比保存对模型本身的引用要好,因为模型可能会更改。

You can access the controller and from the controller the model. 您可以访问控制器,也可以从控制器访问模型。

this.get('controller').get('model') or you can also pass a context to your view, which could be your model. this.get('controller').get('model')或您也可以将上下文传递给视图,该上下文可以是您的模型。 {{view Scrum.Sortable context=this}} {{查看Scrum.Sortable context = this}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM